本例演示使用16进制对数据进行编码
先定义几个工具函数用于将数字转为16进制表示或者将16进制表示转换为数字:
//* 将数字转为16进制(大写)
inline char ToHexUpper(unsigned int value)
{
return "0123456789ABCDEF"[value & 0xF];
}
//* 将数字转为16进制(小写)
inline char ToHexLower(unsigned int value)
{
return "0123456789abcdef"[value & 0xF];
}
//* 将数16进(大写或小写)制转为数字
inline int FromHex(unsigned int c)
{
return ((c >= '0') && (c <= '9')) ? int(c - '0') :
((c >= 'A') && (c <= 'F')) ? int(c - 'A' + 10) :
((c >= 'a') && (c <= 'f')) ? int(c - 'a' + 10) :
/* otherwise */ -1;
}
将数据进行16进制编码:
//* 将数据d用16进制编码,返回值即是结果
std::string HexEncode(const std::string& d)
{
std::string hex;
hex.resize(d.size() * 2);
char* pHexData = (char*)hex.data();
const unsigned char* pSrcData = (const unsigned char*)d.data();
for(int i = 0; i < d.size(); i++)
{
pHexData[i*2] = ToHexLower(pSrcData[i] >> 4);
pHexData[i*2 + 1] = ToHexLower(pSrcData[i] & 0xf);
}
return hex;
}
将数据按照16进制解码
//* 将数据d用16进制解码,返回值即是结果
std::string HexDecode(const std::string& hex)
{
std::string res;
res.resize(hex.size() + 1 / 2);
unsigned char* pResult = (unsigned char*)res.data() + res.size();
bool odd_digit = true;
for(int i = hex.size() - 1; i >= 0; i--)
{
unsigned char ch = unsigned char(hex.at(i));
int tmp = FromHex(ch);
if (tmp == -1)
continue;
if (odd_digit) {
--pResult;
*pResult = tmp;
odd_digit = false;
} else {
*pResult |= tmp << 4;
odd_digit = true;
}
}
res.erase(0, pResult - (unsigned char*)res.data());
return res;
}
使用举例:
std::string str = "你好世界。";
printf("%s\n", str.c_str());
std::string str_hex = HexEncode(str);
printf("%s\n", str_hex.c_str());
std::string str_from_hex = HexDecode(str_hex);
printf("%s\n", str_from_hex.c_str());
结果: