我正在尝试输出 char 的十六进制值并以一种很好的方式对其进行格式化。
必需:0x01:值 0x1
我所能得到的是:00x1 : value 0x1
//如果我不使用 iomanip,则为 0x1
这是我的代码,“ch”被声明为无符号字符。除了检查值并手动添加“0”之外,还有其他方法吗??
cout << showbase;
cout << hex << setw(2) << setfill('0') << (int) ch;
编辑:
我在网上找到了一个解决方案:
cout << internal << setw(4) << setfill('0') << hex << (int) ch
最佳答案
std::cout << "0x" << std::noshowbase << std::hex << std::setw(2) << std::setfill('0') << (int)ch;
由于 setw
填充到整个打印数字的左侧(在应用 showbase
之后),showbase
在您的案子。相反,手动打印出如上所示的基础。
关于C++ 十六进制数字格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1619631/