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::stringstreamthe following example produces
-65538as its result:In the new C++11 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::stringSo, 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 :-).
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_castand 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: