开发者

Cannot display in hexadecimal

开发者 https://www.devze.com 2023-02-27 00:19 出处:网络
unsigned int i = 0x02081; cout << std::hex << i; This displays 2081 when compiled 开发者_运维问答with VS2010 but I think it should display 0x02081. Am I right, and if so, how can this be
unsigned int i = 0x02081;
cout << std::hex << i;

This displays 2081 when compiled 开发者_运维问答with VS2010 but I think it should display 0x02081. Am I right, and if so, how can this be fixed?


By default the base is not printed:

cout << std::hex << std::showbase << i;


The easiest solution, of course, is:

cout << "0x" << std::hex << i; 

Leading zeroes can vary in amount because they don't matter. You can choose any amount you like.


I think it should display 0x02081. Am I right

No, you're not. It will display the value in hex, which is 2081. The 0x isn't part of the number, per se, it's just a notational convenience. The leading zero is also not a part of the number.

If you want the exact output you said you expected, you can do this:

cout << std::hex << std::showbase << std::setw(5) << std::setfill('0') << i;


It should display the value of i as a hexadecimal number - and does so. The prefix 0x is just something some programming languages use to indicate that a literal should be considered hexadecimal.

cout << "0x" << std::hex << i;

As Let_Me_Be points out: "0x" << std::hex could be replaced with std::hex << std::showbase if you want automatic printing of 0x/0/nothing for hex/octal/decimal.

0

精彩评论

暂无评论...
验证码 换一张
取 消