Possible Duplicate:
C++ convert hex string to signed integer
I'm trying to convert a hex string to an unsigned int in C++. My code looks like this:
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.
thanks, Jeff
You can do this using an istringstream
and the hex
manipulator:
#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.
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:
std::cout << value << std::endl; // Knows 'value' is unsigned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With