#include <iostream>
using namespace std;
#include <iomanip>
//单个字符转换为十六进制表示
/*
"314D63" == > "1Mc"
过程:
'3' (0x33)==> 0x3,
'1' (0x31)==> 0x1,
'4' (0x34)==> 0x4,
'D' (0x44)==> 0xD,
'6' (0x36)==> 0x6,
'3' (0x33)==> 0x3,
*/
unsigned char Char2Hex(unsigned char ucTemp)
{
unsigned char ucResult = 0;
if(ucTemp >= '0' && ucTemp <= '9')
{
ucResult = ucTemp - '0';
}
else if(ucTemp >= 'a' && ucTemp <= 'f')
{
ucResult = ucTemp - 'a' + 10;
}
else if(ucTemp >= 'A' && ucTemp <= 'F')
{
ucResult = ucTemp - 'A' + 10;
}
//hex只对整数起作用
cout<< __FUNCTION__ << " " << hex <<(unsigned int)ucTemp << " "
<< hex <<(unsigned int)ucResult << endl;
return ucResult;
}
//"314D63" == > "1Mc"
//"31323361627A" == > "123abz"
//16进制明文字符串"314D63",hex:{33 31 34 44 36 33 == > 16进制{31 4D 63},字符串"1Mc"
string HexToString(string &hexString)
{
string strRet;
if(hexString.empty())
{
return strRet;
}
unsigned char ucResult = 0;
for(int i = 0; i< hexString.size(); i+=2)
{
//两位组成一个字节
/*
'3' (0x33)==> 0x3, '1' (0x31)==> 0x1, ==>组成0x31
*/
ucResult = Char2Hex(hexString[i])*0x10 + Char2Hex(hexString[i+1]);
cout << __FUNCTION__<<" ucResult hex "<<hex <<(unsigned int)ucResult << endl;
strRet += ucResult;//把16进制组合在一起,{0x31,0x4D,0x63}==>结果就是 "1Mc"
}
return strRet;
}
int main()
{
//明文字符串"314D63",hex:{33 31 34 44 36 33 == > 16进制{31 4D 63},字符串"1Mc"
string hexStr1 = "314D63";
string asciiStr1 = HexToString(hexStr1);
cout<< "asciiStr1 == "<< asciiStr1 << endl<< endl;
//"31323361627A" == > "123abz"
string hexStr2 = "31323361627A";//"000300200002db";//"31323361627A";
string asciiStr2 = HexToString(hexStr2);
cout<< "asciiStr2 == "<< asciiStr2 << endl;
return 0;
}
/*
Char2Hex 33 3
Char2Hex 31 1
HexToString ucResult hex 31
Char2Hex 34 4
Char2Hex 44 d
HexToString ucResult hex 4d
Char2Hex 36 6
Char2Hex 33 3
HexToString ucResult hex 63
asciiStr1 == 1Mc
Char2Hex 33 3
Char2Hex 31 1
HexToString ucResult hex 31
Char2Hex 33 3
Char2Hex 32 2
HexToString ucResult hex 32
Char2Hex 33 3
Char2Hex 33 3
HexToString ucResult hex 33
Char2Hex 36 6
Char2Hex 31 1
HexToString ucResult hex 61
Char2Hex 36 6
Char2Hex 32 2
HexToString ucResult hex 62
Char2Hex 37 7
Char2Hex 41 a
HexToString ucResult hex 7a
asciiStr2 == 123abz
*/