在项目中,对豹纹进行压缩、加密后,最后一步一般是 base64 编码。因为 base64 编码的字符串更适合不同平台,不同语言的传输。
base64 编码的优点:
计算机中任何数据都是 ASCII 码存储的, ascii 是 128-255 之间的不可见字符。在网络上进行数据交换,从 A 到 B, 往往要经过多个路由器,不同设备之间对字符的处理方式有一些不同,不可见字符有可能被错误处理,是不利于传输的,因此要先做一个 base64 编码,变成可见字符,这样出错的可能性比较大。
在这里插入图片描述
看看英文版怎么说:
When you have some binary data that you want to ship across a network, you generally don't do it by just streaming the bits and bytes over the wire in a raw format. Why? because some media are made for streaming text. You never know -- some protocols may interpret your binary data as control characters (like a modem), or your binary data could be screwed up because the underlying protocol might think that you've entered a special character combination (like how FTP translates line endings). So to get around this, people encode the binary data into characters. Base64 is one of these types of encodings. Why 64? Because you can generally rely on the same 64 characters being present in many character sets, and you can be reasonably confident that your data's going to end up on the other side of the wire uncorrupted.
base64.h
#include "Base64.h"
const std::string CBase64::base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
int CBase64::find_utf_8_bit_head(const unsigned char *src_content,int src_size )
{
int i_ret = -1;
int byteNum = 0; //字符数
if( src_content )
{
for(int i = src_size-1; i >= 0; i--)
{
if( 0 == (src_content[i] >> 7 ) )
{
byteNum = 1;
i_ret = src_size - i;
break;
}
if( 0x06 == (src_content[i]>> 5) )
{
byteNum = 2;
i_ret = src_size - i;
break;
}
if( 0x0E == (src_content[i] >> 4) )
{
byteNum = 3;
i_ret = src_size - i;
break;
}
if( 0x1E == (src_content[i] >> 3) )
{
byteNum = 4;
i_ret = src_size - i;
break;
}
if( 0x3E == (src_content[i] >> 2) )
{
byteNum = 5;
i_ret = src_size - i;
break;
}
if( 0x7E == (src_content[i] >> 1) )
{
byteNum = 6;
i_ret = src_size - i;
break;
}
}
if( i_ret == byteNum ) i_ret = -1;
}
return i_ret;
}
std::string CBase64::base64_encode(const unsigned char* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '