I will have a string that will contain a 32 bit integer in two's complement notation. The integer can be in decimal(e.g 2123) or in hexadecimal format(e.g. 0xf0000000). The goal is to convert it into int. If an overflow or underflow occurs (e.g. 2147483648) the program must throw an error.
Note: since it's in 32 bit two's complement, the value of 0xfffffffd will be -3 not 268435473. For normal decimal values a minus(-) sign will indicate that the value is negative(duh!).
I have tried strtol with errno, but it returns positive values for all hexadecimal values. And sscanf() cannot check overflow. For the moment I have implemented hex and dec separately in my main program. I used strtol with errno for decimal values. For hex I have checked if the string size() returns <= 10(including 0x) or not, and if it is I have used sscanf() to turn it into int. It works, but I was looking for a more elegant solution that combines both dec and hex.
Code:
#include<iostream>
#include<cerrno>
#include<string>
#include<cstdlib>
using namespace std;
//0000 0000 0000 0000 0000 0000 0000 0011 = 3
//1111 1111 1111 1111 1111 1111 1111 1101 = -3
//f f f f f f f d
int main()
{
string s = "0xfffffffd";
int value = strtol(s.c_str(), NULL, 0);
if(errno == ERANGE)
{
cout<<"Overflow"<<endl;
//exit(1);
}
cout<<"using strtol: "<<value<<endl;
sscanf(s.c_str(), "%x", &value);
cout<<"using sscanf: "<<value<<endl;
return 0 ;
}
Thank you.