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 111111
Working example with strtoul
will be:
#include
#include
using namespace std;
int main() {
string s = "fffefffe";
char * p;
long n = strtoul( s.c_str(), & p, 16 );
if ( * p != 0 ) {
cout << "not a number" << endl;
} else {
cout << n << endl;
}
}
strtol
converts string
to long
. On my computer numeric_limits
gives 0x7fffffff
. Obviously that 0xfffefffe
is greater than 0x7fffffff
. So strtol
returns MAX_LONG
instead of wanted value. strtoul
converts string
to unsigned 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 with strtol
:
#include
#include
using namespace std;
int main() {
string s = "-0x10002";
char * p;
long n = strtol( s.c_str(), & p, 16 );
if ( * p != 0 ) {
cout << "not a number" << endl;
} else {
cout << n << endl;
}
}
The code above prints -65538
in console.