0%

base64编解码--C语言实现

最近项目需要在传输数据的时候进行base64编码传输,在此记录一下实现过程
下边是具体的实现源码

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
static const char *ALPHA_BASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

char *encode(const char *buf, const long size, char *base64Char) {
int a = 0;
int i = 0;
while (i < size) {
char b0 = buf[i++];
char b1 = (i < size) ? buf[i++] : 0;
char b2 = (i < size) ? buf[i++] : 0;

int int63 = 0x3F; // 00111111
int int255 = 0xFF; // 11111111
base64Char[a++] = ALPHA_BASE[(b0 >> 2) & int63];
base64Char[a++] = ALPHA_BASE[((b0 << 4) | ((b1 & int255) >> 4)) & int63];
base64Char[a++] = ALPHA_BASE[((b1 << 2) | ((b2 & int255) >> 6)) & int63];
base64Char[a++] = ALPHA_BASE[b2 & int63];
}
switch (size % 3) {
case 1:
base64Char[--a] = '=';
case 2:
base64Char[--a] = '=';
}
return base64Char;
}

char *decode(const char *base64Char, const long base64CharSize, char *originChar, long originCharSize) {
int toInt[128] = {-1};
for (int i = 0; i < 64; i++) {
toInt[ALPHA_BASE[i]] = i;
}
int int255 = 0xFF;
int index = 0;
for (int i = 0; i < base64CharSize; i += 4) {
int c0 = toInt[base64Char[i]];
int c1 = toInt[base64Char[i + 1]];
originChar[index++] = (((c0 << 2) | (c1 >> 4)) & int255);
if (index >= originCharSize) {
return originChar;
}
int c2 = toInt[base64Char[i + 2]];
originChar[index++] = (((c1 << 4) | (c2 >> 2)) & int255);
if (index >= originCharSize) {
return originChar;
}
int c3 = toInt[base64Char[i + 3]];
originChar[index++] = (((c2 << 6) | c3) & int255);
}
return originChar;
}