1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| #include<iostream> using namespace std; static const char BASE16_ENC_TAB[] = "0123456789ABCDEF"; static const char BASE16_DEC_TAB[128] = { -1, -1,-1,-1,-1,-1, -1,-1,-1,-1,-1, -1,-1,-1,-1,-1, -1,-1,-1,-1,-1, -1,-1,-1,-1,-1, -1,-1,-1,-1,-1, -1,-1,-1,-1,-1, -1,-1,-1,-1,-1, -1,-1,-1,-1,-1, -1,-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1,-1,-1, -1,-1,-1,-1,10, 11,12,13,14,15,
}; int Base16Encode(const unsigned char* in, int size, char* out) {
for (int i = 0; i < size; i++) { char h = in[i] >> 4; char l = in[i] & 0x0F; out[i * 2] = BASE16_ENC_TAB[h]; out[i * 2 + 1] = BASE16_ENC_TAB[l]; } return size * 2; } int Base16Decode(const string &in, unsigned char* out) { for (int i = 0; i < in.size(); i += 2) { unsigned char ch = in[i]; unsigned char cl = in[i + 1]; unsigned char h = BASE16_DEC_TAB[ch]; unsigned char l = BASE16_DEC_TAB[cl];
out[i / 2] = (h << 4) | l; } return in.size() / 2; } int main() {
cout << "Test Base16" << endl; const unsigned char data[] = "测试Base16"; int len = sizeof(data); char out1[1024] = { 0 }; unsigned char out2[1024] = { 0 }; int re = Base16Encode(data, len, out1); cout << re << endl; re = Base16Decode(out1, out2); cout << re << ":" << out2 << endl;
return 0; }
|