获取包含给定数字的十六进制表示的字符串的C -ish方法是对流使用十六进制修饰符,如本例所示:
const int i = 0xdeadbeef;
cout << "0x" << hex << i << endl; // prints "0xdeadbeef"
您可以在字符串流中使用相同的修饰符,以防需要在字符串变量中使用十六进制表示形式:
const int i = 0xdeadc0de;
ostringstream stream;
stream << "0x" << hex << i;
const string s = stream.str(); // s now contains "0xdeadc0de"
更新:
如果您的输入数据以包含字符串字符的十六进制表示形式的字符串给出,则需要知道输入字符串的编码才能正确显示.在最简单的情况下,字符串类似ASCII,将一个字节映射到一个字符.因此,在给定输入“414243”中,每两个字符(“41”,“42”,“43”)映射到ASCII值(65,66,67),其映射到字符(“A”,“B”,“C”).
C:
const string hexData = "414243";
assert( hexData.size() % 2 == 0 );
ostringstream asciiStream;
istringstream hexDataStream( hexData );
vector buf( 3 ); // two chars for the hex char,one for trailing zero
while ( hexDataStream.good() ) {
hexDataStream.get( &buf[0],buf.size() );
if ( hexDataStream.good() ) {
asciiStream << static_cast( std::strtol( &buf[0],16 ) );
}
}
const string asciiData = asciiStream.str(); // asciiData == "ABC"
使用< cstdlib>中的std :: strtol使这很容易如果您坚持为此使用模板类,请使用std :: stringstream将单个子字符串(如“41”)转换为十进制值(65).