I have the following string:
sThis = "2154910440"; unsigned int iStart=atoi(sThis.c_str());
However the result is
iStart = 2147483647
Does anybody see my mistake?
In the C Programming Language, the strtoul function converts a string to an unsigned long integer. The strtoul function skips all white-space characters at the beginning of the string, converts the subsequent characters as part of the number, and then stops when it encounters the first character that isn't a number.
The simple answer is to use strtoul() instead. The longer answer is that even if all you needed was signed 32 bit integers or were happy with 31 bits for unsigned, the atoi() function is a poor fit for what you appear to be doing. As you have already noted, the atoi() function converts a string to an integer.
If you mix signed and unsigned int, the signed int will be converted to unsigned (which means a large positive number if the signed int has a negative value).
You can convert an int to an unsigned int . The conversion is valid and well-defined. Since the value is negative, UINT_MAX + 1 is added to it so that the value is a valid unsigned quantity. (Technically, 2N is added to it, where N is the number of bits used to represent the unsigned type.)
atoi
converts a string to an int
. On your system, an int
is 32 bits, and its max value is 2147483647. The value you are trying to convert falls outside this range, so the return value of atoi
is undefined. Your implementation, I guess, returns the max value of an int
in this case.
You could instead use atoll
, which returns a long long, which is guaranteed to be at least 64 bits. Or you could use a function from the stoi/stol/stoll
family, or their unsigned counterparts, which will actually give useful error reports on out of range values (and invalid values) in the form of exceptions.
Personally, I like boost::lexical_cast
. Even though it appears a bit cumbersome, it can be used in a more general context. You can use it in templates and just forward the type argument instead of having to have specializations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With