C++對資料進行16進位制編碼&解碼(hex encode)
阿新 • • 發佈:2020-12-22
本例演示使用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());
結果: