Converting String to Hex Throws Error: 'std::out_of_range'

Viewed 148

I have a really simple program that converts a hex string to it's int value. The code seems fine, but it throws a runtime error:

terminate called after throwing an instance of 'std::out_of_range' what(): stoi

Here is the code where the error is being caused:

int dump[4];
string hexCodes[4] = {"fffc0000", "ff0cd044", "ff0000fc", "ff000000"};
for (int i = 0; i < 4; i++)
{
    dump[i] = 0;
    dump[i] = stoi(hexCodes[i], 0, 16);
    cout << dump[i] << endl;
}

I have tried reading a couple of pages such as this. I still can't find anything that relates to my issue. What am I doing wrong that is causing this error?

1 Answers

stoi will throw out_of_range if the value is not in the range that int can represent. The number 0xfffc0000 (4294705152) is not in that range for a 32-bit int as it is greater than 2^31-1 (2147483647). So throwing the exception is precisely what it must do.

unsigned would work, but there is no stou, so use stoul. You then probably want to use unsigned dump[4] since you know the value can be represented by an unsigned int. (Again, as long as they are 32 bits on your system. uint32_t might be safer.) As a bonus, this will ensure that cout << dump[i] prints out 4294705152 as desired.

(If you switch to stoul but keep dump as an array of int, the value will be converted to int by the assignment. Under C++20, and for most common systems under earlier C++ standards, the conversion will "wrap around" to -262144, and outputting dump[i] with << will print it out just that way, as a signed integer with a minus sign. So that doesn't seem to be what you want.)

Related