I want to convert a hex string to a 32 bit signed integer in C++.
So, for example, I have the hex string "fffefffe". The binary representation of this is 11111111111111101111111111111110. The signed integer representation of this is: -65538.
How do I do this conversion in C++? This also needs to work for non-negative numbers. For example, the hex string "0000000A", which is 00000000000000000000000000001010 in binary, and 10 in decimal.
use
std::stringstream
the following example produces
-65538
as its result:EDIT: C++11 update. In the new standard, there are a few new utility functions which you can make use of! specifically, there is a family of "string to number" functions (http://en.cppreference.com/w/cpp/string/basic_string/stol and http://en.cppreference.com/w/cpp/string/basic_string/stoul). These are essentially thin wrappers around C's string to number conversion functions, but know how to deal with a
std::string
So, the simplest answer for newer code would probably look like this:
NOTE: Below is my original answer, which as the edit says is not a complete answer. For a functional solution. Stick the code above the line :-).
EDIT: It appears that since
lexical_cast<>
is defined to have stream conversion semantics. Sadly, streams don't understand the "0x" notation. So both theboost::lexical_cast
and my hand rolled one don't deal well with hex strings. The above solution which manually sets the input stream to hex will handle it just fine.Boost has some stuff to do this as well, which has some nice error checking capabilities as well. You can use it like this:
If you don't feel like using boost, here's a light version of lexical cast which does no error checking:
which you can use like this:
another method
This worked for me:
Working example with
strtoul
will be:strtol
convertsstring
tolong
. On my computernumeric_limits<long>::max()
gives0x7fffffff
. Obviously that0xfffefffe
is greater than0x7fffffff
. Sostrtol
returnsMAX_LONG
instead of wanted value.strtoul
convertsstring
tounsigned long
that's why no overflow in this case.Ok,
strtol
is considering input string not as 32-bit signed integer before convertation. Funny sample withstrtol
:The code above prints
-65538
in console.For a method that works with both C and C++, you might want to consider using the standard library function strtol().
I had the same problem today, here's how I solved it so I could keep lexical_cast<>
(Found this page when I was looking for a less sucky way :-)
Cheers, A.