base64编码原理:
采用64个基本的ASCII码字符对数据进行重新编码,它将需要编码的数据拆成字节数,以三个为一族,按照顺序排列24位数据,再把这24位数据分成4组,每组6位,再在每组的最高位补2个0凑足一个字节,如所需的编码数据的字节数不是3的整数,也就是说在分组时最后一组不够3个字节的,在最后一组填充1-2个0字节,并在最后编码完成之后在结尾添加1-2个'='
实现源代码如下
- static const char cb64[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- void base64encode(char*out,const unsigned char* in,int len)
- {
- for(;len >= 3; len -= 3)
- {
- *out++ = cb64[in[0]>>2];
- *out++ = cb64[((in[0]&0x03)<<4)|(in[1]>>4)];
- *out++ = cb64[((in[1]&0x0f)<<2)|((in[2]&0xc0)>>6)];
- *out++ = cb64[in[2]&0x3f];
- in += 3;
- }
- if(len > 0)
- {
- unsigned char fragment;
- fragment = (in[0]&0x03)<<4 ;
- if(len > 1)
- fragment |= in[1]>>4;
- *out++ = cb64[in[0]>>2];
- *out++ = cb64[fragment];
- *out++ = (len < 2)? '=' : cb64[(in[1]&0x0f)<<2];
- *out++ = '=';
- }
- *out = '\0';
- }
转载于:https://blog.51cto.com/scalpel00/289148