C++ 如何使用 stringstream 格式化十六进制数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25143146/
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
how to format hex numbers using stringstream
提问by mtijn
I am trying to convert an unsigned short to its hexadecimal representation in uppercase and prefixed with 0's using stringstream. I can't seem to get the uppercase and 0's correct. here is what I have now:
我正在尝试使用 stringstream 将 unsigned short 转换为大写的十六进制表示形式,并以 0 为前缀。我似乎无法得到正确的大写和 0。这是我现在所拥有的:
USHORT id = 1127;
std::stringstream ss;
ss << std::showbase << std::uppercase << std::setfill('0') << std::setw(4) << std::hex << id;
std::string result = ss.str();
this results in the prefixed '0x' base also being uppercase but I want that to be lowercase. it also results in no prefixed 0's to the hexadecimal value after the prefixed 0x base (currently 0X). for example, this will now output 0X467 instead of the expected 0x0467. how do I fix this?
这导致前缀为“0x”的基数也是大写的,但我希望它是小写的。它还导致前缀 0x 基数(当前为 0X)之后的十六进制值没有前缀 0。例如,现在将输出 0X467 而不是预期的 0x0467。我该如何解决?
回答by Praetorian
setw
is going to set the width of the entire formatted output, including the displayed base, which is why you're not seeing the leading 0
. Also, there's no way to make the base be displayed in lowercase if you use std::showbase
along with std::uppercase
. The solution is to insert the base manually, and then apply the remaining manipulators.
setw
将设置整个格式化输出的宽度,包括显示的基数,这就是为什么你没有看到领先的0
. 此外,如果您std::showbase
与std::uppercase
. 解决方法是手动插入底座,然后应用剩余的机械手。
ss << "0x" << std::uppercase << std::setfill('0') << std::setw(4) << std::hex << id;
This outputs 0x0467
这输出 0x0467