Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ hex string to unsigned int [duplicate]

Tags:

c++

int

hex

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

like image 510
Jeff Storey Avatar asked Jan 26 '11 03:01

Jeff Storey


1 Answers

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.
like image 171
templatetypedef Avatar answered Oct 02 '22 00:10

templatetypedef