• 编码

    1、取待编码字符串前3位(8bit/位),转换为二进制的ascii编码(共24bit)。

    2、将转换后的二进制编码按每6位分为4块,将每块二进制转换成ascii码值

    3、对照base64解码表即可得到对应的base64编码

    4、若取不到3位待编码字符串则用0补充,划分区间后全0的块用‘=’代替

    nw4fN6.png

  • 解码

    1、取待解码字符串前4位(8bit/位),对照base64编码表,转换为映射的数字,并将每一个数转成6位二进制数(共24bit),

    2、将24位二进制分为3份8bit数据

    3、对照ascii码表转换对应字符,解码完成

    4、在第一步中若有‘=’字符则将其转为000000

    Q2PWVJ.png

附base64编码对照表

nw4Hud.png

base64_decode

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
const char * base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";//可以自己定制,比如说把+和/改成-和_以满足url编码的要求。
int base64_decode( const char * base64, unsigned char * bindata )
{
int i, j;
unsigned char k;
unsigned char t;
unsigned char temp[4];
for ( i = 0, j = 0; base64[i] != '\0' ; i += 4 )//每四个字节为一组
{
memset( temp, 0xFF, sizeof(temp) );
for ( k = 0 ; k < 64 ; k ++ )
{
if ( base64char[k] == base64[i] )
temp[0]= k;//获取一组中每个字节对应的编号
}
for ( k = 0 ; k < 64 ; k ++ )
{
if ( base64char[k] == base64[i+1] )
temp[1]= k;
}
for ( k = 0 ; k < 64 ; k ++ )
{
if ( base64char[k] == base64[i+2] )
temp[2]= k;
}
for ( k = 0 ; k < 64 ; k ++ )
{
if ( base64char[k] == base64[i+3] )
temp[3]= k;
}

bindata[j++] = ((unsigned char)(((unsigned char)(temp[0] << 2))&0xFC)) |((unsigned char)((unsigned char)(temp[1]>>4)&0x03));//这些就是补0补位的操作了

if ( base64[i+2] == '=' )
break;

bindata[j++] = ((unsigned char)(((unsigned char)(temp[1] << 4))&0xF0)) | ((unsigned char)((unsigned char)(temp[2]>>2)&0x0F));

if ( base64[i+3] == '=' )
break;

bindata[j++] = ((unsigned char)(((unsigned char)(temp[2] << 6))&0xF0)) |((unsigned char)(temp[3]&0x3F));

}
return j;
}

base64_encode

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
char * base64_encode( const unsigned char * bindata, char * base64, int binlength )
{
int i, j;
unsigned char current;

for ( i = 0, j = 0 ; i < binlength ; i += 3 )
{
current = (bindata[i] >> 2) ;
current &= (unsigned char)0x3F;
base64[j++] = base64char[(int)current];

current = ( (unsigned char)(bindata[i] << 4 ) ) & ( (unsigned char)0x30 ) ;
if ( i + 1 >= binlength )
{
base64[j++] = base64char[(int)current];
base64[j++] = '=';
base64[j++] = '=';
break;
}
current |= ( (unsigned char)(bindata[i+1] >> 4) ) & ( (unsigned char) 0x0F );
base64[j++] = base64char[(int)current];

current = ( (unsigned char)(bindata[i+1] << 2) ) & ( (unsigned char)0x3C ) ;
if ( i + 2 >= binlength )
{
base64[j++] = base64char[(int)current];
base64[j++] = '=';
break;
}
current |= ( (unsigned char)(bindata[i+2] >> 6) ) & ( (unsigned char) 0x03 );
base64[j++] = base64char[(int)current];

current = ( (unsigned char)bindata[i+2] ) & ( (unsigned char)0x3F ) ;
base64[j++] = base64char[(int)current];
}
base64[j] = '\0';
return base64;
}