10 static char *base64_encode(const char *buf, int len)
12 const char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
13 int bit_offset, byte_offset, idx, i;
14 const unsigned char *d = (const unsigned char *)buf;
15 int bytes = (len*8 + 5)/6, pad_bytes = (bytes % 4) ? 4 - (bytes % 4) : 0;
18 out = calloc(1, bytes+pad_bytes+1);
19 if (!out) return NULL;
21 for (i=0;i<bytes;i++) {
22 byte_offset = (i*6)/8;
25 idx = (d[byte_offset] >> (2-bit_offset)) & 0x3F;
27 idx = (d[byte_offset] << (bit_offset-2)) & 0x3F;
28 if (byte_offset+1 < len) {
29 idx |= (d[byte_offset+1] >> (8-(bit_offset-2)));
35 for (;i<bytes+pad_bytes;i++)
43 static int load_stdin(char **s)
51 int n = read(0, buf, sizeof(buf));
52 if (n == -1 && errno == EINTR) continue;
55 (*s) = realloc((*s), length + n + 1);
58 memcpy((*s)+length, buf, n);
67 int main(int argc, char *argv[])
74 printf("%s\n", base64_encode(s, n));