Files
libucore/src/base64_dec.c
T
2013-03-06 22:22:04 +01:00

53 lines
1.8 KiB
C

#include <stdint.h>
#include "ucore/string.h"
static const uint8_t basecode[128] =
{
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 62, 0xff, 0xff, 0xff, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0xff, 0xff, 0xff, 0xff, 0xff
};
#define deccode(c) ((c > 127) ? 0xff : basecode[(c)])
size_t
uc_base64_dec(const unsigned char *data, size_t len, unsigned char *result)
{
size_t i = 0, j = 0, pad;
uint8_t c[4];
while ((i + 3) < len) {
pad = 0;
c[0] = deccode(data[i ]); pad += (c[0] == 0xff);
c[1] = deccode(data[i+1]); pad += (c[1] == 0xff);
c[2] = deccode(data[i+2]); pad += (c[2] == 0xff);
c[3] = deccode(data[i+3]); pad += (c[3] == 0xff);
switch (pad) {
case 1:
result[j++] = (c[0] << 2) | ((c[1] & 0x30) >> 4);
result[j++] = ((c[1] & 0x0f) << 4) | ((c[2] & 0x3c) >> 2);
result[j] = (c[2] & 0x03) << 6;
break;
case 2:
result[j++] = (c[0] << 2) | ((c[1] & 0x30) >> 4);
result[j] = (c[1] & 0x0f) << 4;
break;
default:
result[j++] = (c[0] << 2) | ((c[1] & 0x30) >> 4);
result[j++] = ((c[1] & 0x0f) << 4) | ((c[2] & 0x3c) >> 2);
result[j++] = ((c[2] & 0x03) << 6) | (c[3] & 0x3f);
}
i += 4;
}
return j;
}