2009-10-25 84 views
9

我试图输出一个字符的十六进制值并以很好的方式对其进行格式化。C++十六进制数字格式

要求:0x01 : value 0x1

我能得到的是:00x1 : value 0x1 //或为0x1,如果我不使用了iomanip

下面的代码我有,“CH”被宣布为一个无符号的字符。除检查值并手动添加'0'以外,还有其他方法可以实现吗?

cout << showbase; 
cout << hex << setw(2) << setfill('0') << (int) ch; 

编辑:

我发现一种解决方案在线:

cout << internal << setw(4) << setfill('0') << hex << (int) ch 

回答

13
std::cout << "0x" << std::noshowbase << std::hex << std::setw(2) << std::setfill('0') << (int)ch; 

由于setw垫出整个打​​印的数量的左侧(施加showbase后),showbase ISN在你的情况下无法使用。相反,如上所示手动打印底座。

0

在一个对我的项目,我这样做:

ostream &operator<<(ostream &stream, byte value) 
{ 
    stream << "0x" << hex << (int)value; 
    return stream; 
} 

我surchaged操作< <的流输出,以及任何这是一个字节是十六进制表示。字节是unsigned char的typedef。