C++ 十六进制字符串到无符号整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4801146/
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++ hex string to unsigned int
提问by Jeff Storey
Possible Duplicate:
C++ convert hex string to signed integer
可能的重复:
C++ 将十六进制字符串转换为有符号整数
I'm trying to convert a hex string to an unsigned int in C++. My code looks like this:
我正在尝试在 C++ 中将十六进制字符串转换为无符号整数。我的代码如下所示:
string hex("FFFF0000");
UINT decimalValue;
sscanf(hex.c_str(), "%x", &decimalValue);
printf("\nstring=%s, decimalValue=%d",hex.c_str(),decimalValue);
The result is -65536 though. I don't typically do too much C++ programming, so any help would be appreciated.
结果是-65536。我通常不会做太多的 C++ 编程,所以任何帮助将不胜感激。
thanks, Jeff
谢谢,杰夫
回答by templatetypedef
You can do this using an istringstream
and the hex
manipulator:
您可以使用 anistringstream
和hex
操纵器执行此操作:
#include <sstream>
#include <iomanip>
std::istringstream converter("FFFF0000");
unsigned int value;
converter >> std::hex >> value;
You can also use the std::oct
manipulator to parse octal values.
您还可以使用std::oct
操纵器来解析八进制值。
I think the reason that you're getting negative values is that you're using the %d
format specifier, which is for signed values. Using %u
for unsigned values should fix this. Even better, though, would be to use the streams library, which figures this out at compile-time:
我认为你得到负值的原因是你使用了%d
格式说明符,它用于有符号值。使用%u
无符号值应该解决这个问题。不过,更好的是使用流库,它在编译时计算出这一点:
std::cout << value << std::endl; // Knows 'value' is unsigned.
回答by Will Tate
output with int with %u
instead of %d
用 int 输出%u
而不是%d
回答by ruslik
Well, -65536 is 0xFFFF0000. If you'll use
好吧,-65536 是 0xFFFF0000。如果你会使用
printf("\nstring=%s, decimalValue=%u",hex.c_str(),decimalValue);
it will print what you expect.
它将打印您期望的内容。
回答by Lou Franco
%d
interprets the bits of the UINT as signed. You need:
%d
将 UINT 的位解释为有符号。你需要:
printf("\nstring=%s, decimalValue=%u",hex.c_str(),decimalValue);
回答by Keith Randall
The answer is right, 0xffff0000 is -65536 if interpreted as signed (the %d printf formatter). You want your hex number interpreted as unsigned (%u or %x).
答案是正确的,如果解释为有符号(%d printf 格式化程序),则 0xffff0000 是 -65536。您希望将十六进制数解释为无符号(%u 或 %x)。