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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:13:39  来源:igfitidea点击:

C++ cout hex format

c++

提问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 charas a 'character' that you want to output, and just outputs that byte exactly. The hexonly 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_castwould 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 hexto decsince 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 255instead.

哪个应该给出值255

Further detail related to the the strstream to decshall 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 0xahead of ff. The original reply related to hexnumber printing was in http://www.cplusplus.com/forum/windows/51591/.

<iomanip>如果您想0x提前查看该库,则该库是可选的ff。与hex数字打印相关的原始回复在http://www.cplusplus.com/forum/windows/51591/