44 lines
1.0 KiB
C
44 lines
1.0 KiB
C
#include <stdint.h>
|
|
#include <stdlib.h>
|
|
#include "ucore/string.h"
|
|
|
|
static const char basecode[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
#define PAD '='
|
|
|
|
size_t
|
|
uc_base64_enc(const unsigned char *data,size_t len,unsigned char *result)
|
|
{
|
|
|
|
size_t i = 0, j = 0;
|
|
size_t pad;
|
|
|
|
|
|
while (i < len) {
|
|
pad = 3 - (len - i);
|
|
switch(pad) {
|
|
case 2:
|
|
result[j] = basecode[data[i]>>2];
|
|
result[j+1] = basecode[(data[i] & 0x03) << 4];
|
|
result[j+2] = PAD;
|
|
result[j+3] = PAD;
|
|
break;
|
|
case 3:
|
|
result[j ] = basecode[data[i]>>2];
|
|
result[j+1] = basecode[((data[i] & 0x03) << 4) | ((data[i+1] & 0xf0) >> 4)];
|
|
result[j+2] = basecode[(data[i+1] & 0x0f) << 2];
|
|
result[j+3] = PAD;
|
|
break;
|
|
default:
|
|
result[j ] = basecode[data[i]>>2];
|
|
result[j+1] = basecode[((data[i] & 0x03) << 4) | ((data[i+1] & 0xf0) >> 4)];
|
|
result[j+2] = basecode[((data[i+1] & 0x0f) << 2) | ((data[i+2] & 0xc0) >> 6)];
|
|
result[j+3] = basecode[data[i+2] & 0x3f];
|
|
break;
|
|
}
|
|
j += 4;
|
|
i += 3;
|
|
}
|
|
|
|
return j;
|
|
}
|