一. Base64编码由来
为什么会有Base64编码呢?因为有些网络传送渠道并不支持所有的字节,例如传统的邮件只支持可见字符的传送,像ASCII码的控制字符就 不能通过邮件传送。这样用途就受到了很大的限制,比如图片二进制流的每个字节不可能全部是可见字符,所以就传送不了。最好的方法就是在不改变传统协议的情 况下,做一种扩展方案来支持二进制文件的传送。把不可打印的字符也能用可打印字符来表示,问题就解决了。Base64编码应运而生,Base64就是一种 基于64个可打印字符来表示二进制数据的表示方法。
二. Base64编码原理
看一下Base64的索引表,字符选用了"A-Z、a-z、0-9、+、/" 64个可打印字符。数值代表字符的索引,这个是标准Base64协议规定的,不能更改。64个字符用6个bit位就可以全部表示,一个字节有8个bit 位,剩下两个bit就浪费掉了,这样就不得不牺牲一部分空间了。这里需要弄明白的就是一个Base64字符是8个bit,但是有效部分只有右边的6个 bit,左边两个永远是0。
三. 索引表const char BASE_CODE[] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'};
四.编码
char* Base64::encode(const char *src){
size_t sLength = strlen(src);
size_t dLength = ((sLength%3 == 0 ?0:1)+sLength/3)*4;
char* dest = (char*)malloc(sizeof(char)*(dLength+1));
int count = 0;
for (int i=0; i<=sLength-3; i=i+3) {
unsigned char sc1 = src[i];
unsigned char sc2 = src[i+1];
unsigned char sc3 = src[i+2];
char c1 = sc1>>2;
char c2 = ((unsigned char)(sc1<<6))>>2 | (sc2>>4);
char c3 = ((unsigned char)(sc2<<4))>>2| (sc3>>6);
unsigned char ct4 = sc3<<2;
char c4 = ct4>>2;
printf("%c,%c,%c,%d,%d,%d\n",sc1,sc2,sc3,c1,c2,c3);
dest[count*4] = BASE_CODE[c1];
dest[count*4+1] = BASE_CODE[c2];
dest[count*4+2] = BASE_CODE[c3];
dest[count*4+3] = BASE_CODE[c4];
count++;
}
size_t m = sLength%3;
if(m == 1){
unsigned char sc1 = src[sLength-1];
char c1 = sc1>>2;
char c2 = ((unsigned char)(sc1<<6))>>2;
dest[count*4] = BASE_CODE[c1];
dest[count*4+1] = BASE_CODE[c2];
dest[count*4+2] = '=';
dest[count*4+3] = '=';
}else if(m == 2){
unsigned char sc1 = src[sLength-2];
unsigned char sc2 = src[sLength-1];
char c1 = sc1>>2;
char c2 = ((unsigned char)(sc1<<6))>>2 | (sc2>>4);
char c3 = ((unsigned char)(sc2<<4))>>2;
dest[count*4] = BASE_CODE[c1];
dest[count*4+1] = BASE_CODE[c2];
dest[count*4+2] = BASE_CODE[c3];
dest[count*4+3] = '=';
}
dest[dLength] = '\0';
return dest;
}
五.解码
char* Base64::decode(const char *src){
size_t slength = strlen(src);
size_t dlength = (slength/4)*3;
char* dest = (char*)malloc(sizeof(char)*(dlength+1));
int count = 0;
for (int i=0; i<slength; i = i+4) {
char sc1 = getDecodeValue(src[i]);
char sc2 = getDecodeValue(src[i+1]);
char sc3 = getDecodeValue(src[i+2]);
char sc4 = getDecodeValue(src[i+3]);
unsigned char c1 = sc1<<2 | sc2>>4;
unsigned char c2 = sc2<<4 | sc3>>2;
unsigned char c3 = sc3<<6 | sc4;
dest[count*3] = c1;
dest[count*3+1] = c2;
dest[count*3+2] = c3;
count++;
}
dest[dlength] = '\0';
return dest;
}
char Base64::getDecodeValue(const char src){
char dest = 0;
for(int i=0;i<64;i++){
if (BASE_CODE[i] == src) {
dest = i;
break;
}
}
return dest;
}
参考:http://www.cnblogs.com/chengxiaohui/articles/3951129.html