简体   繁体   English

c ++十六进制数字格式

[英]c++ hex number format

I'm trying to output the hex value of a char and format it in a nice way. 我正在尝试输出char的十六进制值并以一种很好的方式对其进行格式化。

Required: 0x01 : value 0x1 必需: 0x01 : value 0x1

All I can get is: 00x1 : value 0x1 // or 0x1 if i don't use iomanip 我只能得到: 00x1 : value 0x1 //如果我不使用iomanip则为0x1

Here's the code i have, 'ch' was declared to be a unsigned char. 这是我的代码,'ch'被声明为unsigned char。 Is there any other way to do it other than checking the value and manually add an '0'?? 除了检查值并手动添加'0'之外,还有其他方法吗?

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

Edit: 编辑:

I found one solution online: 我在网上找到一个解决方案

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

Since setw pads out to the left of the overall printed number (after showbase is applied), showbase isn't usable in your case. 由于setw showbase到整个打印数字的左侧(在应用showbase之后), showbase在您的情况下不可用。 Instead, manually print out the base as shown above. 而是手动打印出基座,如上所示。

In one on my projects I did this: 在我的项目中,我做到了这一点:

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

I surchaged the operator<< for stream output, and anything that was a byte was shown in hexadecimal. 我为运行<<输出操作符号,并且以十六进制显示任何字节。 byte is a typedef for unsigned char. byte是unsigned char的typedef。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM