C++ cout 十六进制格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3595136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ cout hex format
提问by pdk
i am a c coder, new to c++.
我是 ac 编码员,刚接触 C++。
i try to print the following with cout with strange output. Any comment on this behaviour is appreciated.
我尝试使用带有奇怪输出的 cout 打印以下内容。对此行为的任何评论表示赞赏。
#include<iostream>
using namespace std;
int main()
{
unsigned char x = 0xff;
cout << "Value of x " << hex<<x<<" hexadecimal"<<endl;
printf(" Value of x %x by printf", x);
}
output:
输出:
Value of x ? hexadecimal
Value of x ff by printf
回答by Thanatos
<<
handles char
as a 'character' that you want to output, and just outputs that byte exactly. The hex
only applies to integer-like types, so the following will do what you expect:
<<
处理char
为您要输出的“字符”,并准确地输出该字节。该hex
只适用于整数样的类型,所以下面会做你所期望的:
cout << "Value of x " << hex << int(x) << " hexadecimal" << endl;
Billy ONeal's suggestion of static_cast
would look like this:
Billy ONeal 的建议static_cast
如下:
cout << "Value of x " << hex << static_cast<int>(x) << " hexadecimal" << endl;
回答by Starkey
You are doing the hex part correctly, but x is a character, and C++ is trying to print it as a character. You have to cast it to an integer.
您正确地执行了十六进制部分,但 x 是一个字符,而 C++ 正试图将其打印为一个字符。您必须将其强制转换为整数。
#include<iostream>
using namespace std;
int main()
{
unsigned char x = 0xff;
cout << "Value of x " << hex<<static_cast<int>(x)<<" hexadecimal"<<endl;
printf(" Value of x %x by printf", x);
}
回答by Yeeson
If I understand your question correctly, you should expect to know how to convert hex
to dec
since you have already assigned unsigned char x = 0xff;
如果我正确理解您的问题,您应该知道如何转换hex
为,dec
因为您已经分配了unsigned char x = 0xff;
#include <iostream>
int main()
{
unsigned char x = 0xff;
std::cout << std::dec << static_cast<int>(x) << std::endl;
}
which shall give the value 255
instead.
哪个应该给出值255
。
Further detail related to the the str
stream to dec
shall refer in http://www.cplusplus.com/reference/ios/dec/.
与str
流相关的更多详细信息dec
请参阅http://www.cplusplus.com/reference/ios/dec/。
If you want to know the hexadecimal value from the decimal one, here is a simple example
如果你想知道十进制的十六进制值,这里有一个简单的例子
#include <iostream>
#include <iomanip>
int main()
{
int x = 255;
std::cout << std::showbase << std::setw(4) << std::hex << x << std::endl;
}
which prints oxff
.
打印oxff
.
The library <iomanip>
is optional if you want to see 0x
ahead of ff
. The original reply related to hex
number printing was in http://www.cplusplus.com/forum/windows/51591/.
<iomanip>
如果您想0x
提前查看该库,则该库是可选的ff
。与hex
数字打印相关的原始回复在http://www.cplusplus.com/forum/windows/51591/。