闲来无事,写个base64编码函数玩玩。
资料来源:http://zh.wikipedia.org/wiki/Base64
这东西简单,好像也没必要去阅读RFC,维基上后面提到在URL中应用的修改情况,变化不大,不足为虑。直接上代码及例子:
int getbase64len(const char* src)
{
int len = strlen(src);
return (len+2)/3*4;
}
const char* encode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// 换的时候,将三个byte的数据,先后放入一个24bit的缓冲区中,先来的byte占高位。
// 数据不足3byte的话,于缓冲器中剩下的bit用0补足。然后,每次取出6(因为26=64)个bit,
// 按照其值选择ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/中的字符作为编码后的输出。
// 不断进行,直到全部输入数据转换完成。
int encode_base64(const char* src, char* dest)
{
const char* psrc = src;
char* pdest = dest;
char buff[3];
while (*psrc)
{
buff[0] = *psrc++;
buff[1] = *psrc++;
buff[2] = *psrc++;
if (!buff[1])
{
buff[1] = buff[2] = 0;
*pdest++ = encode[(buff[0]&0xfc)>>2];//取前0-5位
*pdest++ = encode[((buff[0]&0x03)<<4)];
*pdest++ = '=';
*pdest++ = '=';
break;
}
else if (!buff[2])
{
buff[2] = 0;
*pdest++ = encode[(buff[0]&0xfc)>>2];//取前0-5位
*pdest++ = encode[((buff[0]&0x03)<<4)/*取6-7位*/ | ((buff[1]&0xf0)>>4)/*取8-11位*/];
*pdest++ = encode[(buff[1]&0x0f)<<2/*取12-15位*/];
*pdest++ = '=';
break;
}
else
{
// 处理buff,输出到dest中
*pdest++ = encode[(buff[0]&0xfc)>>2];//取前0-5位
*pdest++ = encode[((buff[0]&0x03)<<4)/*取6-7位*/ | ((buff[1]&0xf0)>>4)/*取8-11位*/];
*pdest++ = encode[(buff[1]&0x0f)<<2/*取12-15位*/ | (buff[2]&0xc0)>>6/*取16-17位*/];
*pdest++ = encode[buff[2]&0x3f];//取后6位
}
}
*pdest = 0;
return pdest - dest;
}
应用的例子,内容使用了维基上的测试例子,通过。
int _tmain(int argc, _TCHAR* argv[])
{
char* src = "Man is distinguished, not only by his reason, "
"but by this singular passion from other animals, "
"which is a lust of the mind, that by a perseverance "
"of delight in the continued and indefatigable generation "
"of knowledge, exceeds the short vehemence of any carnal "
"pleasure.";
char* target = "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz"
"IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg"
"dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu"
"dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo"
"ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=";
int destlen = getbase64len(src);
char* dest = new char[destlen+1];
int len = encode_base64(src,dest);
if (0 == strcmp(dest,target))
{
printf("the base64 encode is successed!");
}
getchar();
return 0;
}