Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to unsigned int returns the wrong result

Tags:

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?

like image 302
tmighty Avatar asked Aug 03 '13 22:08

tmighty


People also ask

How do I convert a string to an unsigned int?

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.

Does Atoi work for unsigned int?

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.

What happens when you cast int to Uint?

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).

What happens when you cast an int to an unsigned int?

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.)


1 Answers

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

like image 150
Benjamin Lindley Avatar answered Oct 06 '22 01:10

Benjamin Lindley