6

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

Community
  • 1
  • 1
Jeff Storey
  • 56,312
  • 72
  • 233
  • 406
  • Also see [Convert hexadecimal string with leading “0x” to signed short in C++?](http://stackoverflow.com/q/1487440/608639) – jww May 07 '17 at 04:53

5 Answers5

25

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.
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • Does anyone know what happens here if the number is not valid hex? I just tried letters such as 0xG, and I didn't catch an exception? – gbmhunter Apr 09 '14 at 02:20
  • @gbmhunter That will cause the stream to enter a fail state, which doesn't necessarily trigger an exception unless you've enabled them. You might want to read up on `failbit` and stream failures. – templatetypedef Apr 09 '14 at 02:50
6

output with int with %u instead of %d

Will Tate
  • 33,439
  • 9
  • 77
  • 71
4

Well, -65536 is 0xFFFF0000. If you'll use

printf("\nstring=%s, decimalValue=%u",hex.c_str(),decimalValue);

it will print what you expect.

ruslik
  • 14,714
  • 1
  • 39
  • 40
3

%d interprets the bits of the UINT as signed. You need:

printf("\nstring=%s, decimalValue=%u",hex.c_str(),decimalValue);
ruslik
  • 14,714
  • 1
  • 39
  • 40
Lou Franco
  • 87,846
  • 14
  • 132
  • 192
3

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).

Keith Randall
  • 22,985
  • 2
  • 35
  • 54