问题描述
我已经使用了功能的atoi
字符字符串转换为 INT
和它的正常工作,但是当我给
I have used the function atoi
to convert character strings to int
and it's working fine but when I gave
num = atoi (argv[1]) ;
// argv contain 4294967295 maximun value of 32 bit integer
它给了我答案2147483647这基本上是一半4294967295
it's giving me 2147483647 answer which is basically half of 4294967295
我想这是因为它在字符
字节的区别和 INT
。
能发生了什么,以比特和字节任何一个解释
以及如何修复它或将其转换为int
i guess that its because of difference of bytes in char
and int
.Can any one explain whats happening to bits and bytesand how to fix it or convert it to int
推荐答案
您已经运行到一个整数的最大值。由于的atoi
返回 INT
,它仅限于您的计算机上一个整数的大小。它看起来像你的机器使用32位 INT
秒。
You've run into the maximum value of an integer. Since atoi
returns an int
, it is limited to the size of an integer on your machine. It looks like your machine uses 32-bit int
s.
如果你错过了(很容易错过),2147483647 =(2 ^ 31) - 1,请记住, INT
S可以是负的,而最左边的位是在这种情况下的符号位。这就是为什么你看到的数字是有限到2147483647。
In case you missed it (it's easy to miss), 2147483647 = (2 ^ 31) - 1. Remember that int
s can be negative, and the leftmost bit is the sign bit in that case. That's why you see the number being "limited" to 2147483647.
尝试定义的 NUM
为 unsigned int类型
而不是 INT
,并使用 strtoul将
而不是中的atoi
。
Try defining num
as unsigned int
instead of int
, and use strtoul
instead of atoi
.
这篇关于我们怎样才能将字符串转换为int的非常大的整数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!