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.
Andy Buchanan, as far as sticking to C++ goes, I liked yours, but I have a few mods:
Used like
That way you don't need one impl per int type.
Here's a simple and working method I found elsewhere:
Please note that you might prefer using unsigned long integer/long integer, to receive the value. Another note, the c_str() function just converts the std::string to const char* .
So if you have a const char* ready, just go ahead with using that variable name directly, as shown below [I am also showing the usage of the unsigned long variable for a larger hex number. Do not confuse it with the case of having const char* instead of string]:
This works just perfectly fine (provided you use appropriate data types per your need).