Possible Duplicate:
C++ convert hex string to signed integer
我正在尝试将十六进制字符串转换为 C++ 中的无符号整数。我的代码如下所示:
string hex("FFFF0000");
UINT decimalValue;
sscanf(hex.c_str(), "%x", &decimalValue);
printf("\nstring=%s, decimalValue=%d",hex.c_str(),decimalValue);
虽然结果是 -65536。我通常不会进行过多的 C++ 编程,因此我们将不胜感激。
谢谢,
杰夫
您可以使用 istringstream
和 hex
操纵器执行此操作:
#include <sstream>
#include <iomanip>
std::istringstream converter("FFFF0000");
unsigned int value;
converter >> std::hex >> value;
您还可以使用 std::oct
操纵符来解析八进制值。
我认为您得到负值的原因是您使用的是 %d
格式说明符,它用于有符号值。对无符号值使用 %u
应该可以解决这个问题。不过,更好的方法是使用流库,它会在编译时解决这个问题:
std::cout << value << std::endl; // Knows 'value' is unsigned.