-
Notifications
You must be signed in to change notification settings - Fork 1
/
b64.c
53 lines (45 loc) · 1.17 KB
/
b64.c
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
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
52
53
#include <stdlib.h>
#include "b64.h"
char *
b64_enc(const unsigned char *str, size_t n, size_t *outn)
{
static char const BASE64_CHARS[64] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
size_t i, j;
char *out = malloc((*outn = ((n + 2) / 3) * 4) + 1);
if (out == NULL)
return NULL;
for (i = 0, j = 0; i + 3 <= n; i += 3, j += 4) {
out[j + 0] = BASE64_CHARS[str[i + 0] >> 2];
out[j + 1] = BASE64_CHARS[((str[i + 0] & 0x3U) << 4) | (str[i + 1] >> 4)];
out[j + 2] = BASE64_CHARS[((str[i + 1] & 0xfU) << 2) | (str[i + 2] >> 6)];
out[j + 3] = BASE64_CHARS[str[i + 2] & 0x3fU];
}
switch (n - i) {
default:
#if defined(__GNUC__) || defined(__clang__)
__builtin_unreachable();
#endif
/* FALLTHROUGH */
case 0:
break;
case 1:
out[j + 0] = BASE64_CHARS[str[i + 0] >> 2];
out[j + 1] = BASE64_CHARS[(str[i + 0] & 0x3) << 4];
out[j + 2] = '=';
out[j + 3] = '=';
j += 4;
break;
case 2:
out[j + 0] = BASE64_CHARS[str[i] >> 2];
out[j + 1] = BASE64_CHARS[((str[i] & 0x3) << 4) | (str[i + 1] >> 4)];
out[j + 2] = BASE64_CHARS[(str[i + 1] & 0xf) << 2];
out[j + 3] = '=';
j += 4;
break;
}
out[j] = '\0';
return out;
}