问题描述
我已经使用函数 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
我猜这是因为 char
和 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
s.
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!