MSDN文档中这个错误吗?
这是MSDN链接 来自 http://msdn.microsoft.com/en -us/library/s3f49ktz(v=VS.80).aspx
它说: 无符号整数:4字节 值范围 0 到 4,294,967,295
因此我的测试代码:
void main(void)
{
unsigned int sum; //4byte, 32bit
sum = 2147483648; //2^31 represent by 1 followed by 31 0s
printf("sum is %d\n",sum);
sum = sum -1 ; //2^31-1 represent by 0 followed by 31 1s
printf("sum is %d\n",sum);
getchar();
}
我确信 4,294,967,295=2^32-1,printf 将打印“0”,转储最高有效位 我认为MSDN应该写值范围:0到2147483647 是这样吗?
Here is MSDN link
From http://msdn.microsoft.com/en-us/library/s3f49ktz(v=VS.80).aspx
It says:
unsigned int : 4byte
Range of Value 0 to 4,294,967,295
Hence my test code:
void main(void)
{
unsigned int sum; //4byte, 32bit
sum = 2147483648; //2^31 represent by 1 followed by 31 0s
printf("sum is %d\n",sum);
sum = sum -1 ; //2^31-1 represent by 0 followed by 31 1s
printf("sum is %d\n",sum);
getchar();
}
I am sure 4,294,967,295=2^32-1, printf will print "0", dump most significant bit
I think MSDN should wrote range of value: 0 to 2147483647
Is that right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
文档是正确的。
-2147483648 到 2147483647 (231 - 1) 是有符号 int 的范围。
0 到 4294967295 (232 - 1) 是无符号 int 的范围。
使用
%u
而不是%d
请参阅printf 类型字段字符
The documentation is correct.
-2147483648 to 2147483647 (231 - 1) is the range of a signed int.
0 to 4294967295 (232 - 1) is the range of an unsigned int.
Use
%u
instead of%d
See printf Type Field Characters
这是不正确的,如果你想得到 4b 你应该这样做
或者
这应该给你一个无符号整数的正确的最大值(就像黑客一样)。另外,正如其他人指出的那样,您应该在 printf 中使用 %u 作为格式化程序,以便正确解释该值。
无符号 int 使用所有位作为幅度位,因此前导位不再被视为符号位,因此变为 2^32 - 1 而不是 2^31 - 1
That's incorrect, if you want to get 4b you should do
Alternatively
This should give you the correct max value for an unsigned int (as hackish as that is). Also as others pointed out you should use %u as the formatter in your printf so that the value gets interpreted correctly.
An unsigned int uses all bits as magnitude bits so the leading bit is no longer considered a sign bit so that becomes 2^32 - 1 instead of just 2^31 - 1
正如 Sander 提到的,您需要使用
%u
而不是%d
,因为您正在查看无符号整数而不是有符号整数。负数使用 二进制补码 存储,其中 -1 = 0xFFFFFFFF、-2 = 0xFFFFFFFE 和以此类推到-2^32 = 0x80000000。
如果对 unsigned int 执行 0xFFFFFFFF + 1,则变量中的结果为 0,则会发生溢出(转储额外的位)。
As Sander mentioned, you need to use
%u
instead of%d
since you are looking at unsigned integers instead of signed.Negative numbers are stored using two's complement where -1 = 0xFFFFFFFF, -2 = 0xFFFFFFFE, and so on to -2^32 = 0x80000000.
You would get an overflow (dumping the extra bit) if you did 0xFFFFFFFF + 1 to an unsigned int, with the result in the variable being 0.