波浪号çVS无符号整数签署 [英] Tilde C unsigned vs signed integer
问题描述
例如:
unsigned int i = ~0;
结果:最大数,我可以分配到 I
Result: Max number I can assign to i
和
signed int y = ~0;
结果: 1
为什么我得到 1
?我不应该得到我可以分配给 y中的最大数量
?
Why do I get -1
? Shouldn't I get the maximum number that I can assign to y
?
推荐答案
两个 4294967295
(又名 UINT_MAX
)和 1
具有相同的二进制重新$ p $ 0xFFFFFFFF的
的psentation位或32位全部设置为 1
。这是因为有符号数是使用补重新presented。负数有MSB(最显著位)设置为 1
和翻转位的其余部分,添加 1 $确定其价值C $ C>和乘以
1
。所以,如果你有MSB设置为 1
和位也设置为 1
的其余部分,你将它们翻转(获得32个零),添加 1
(获得 1
)和 1 乘code>终于得到
1
。
Both 4294967295
(a.k.a. UINT_MAX
) and -1
have the same binary representation of 0xFFFFFFFF
or 32 bits all set to 1
. This is because signed numbers are represented using two's complement. A negative number has its MSB (most significant bit) set to 1
and its value determined by flipping the rest of the bits, adding 1
and multiplying by -1
. So if you have the MSB set to 1
and the rest of the bits also set to 1
, you flip them (get 32 zeros), add 1
(get 1
) and multiply by -1
to finally get -1
.
这使得它更容易为CPU做数学题,因为它需要为负数没有特别的异常。例如,尝试添加 0xFFFFFFFF的
(-1)和 1
。由于只有32位的房间,这会溢出,结果将是 0
如预期
This makes it easier for the CPU to do the math as it needs no special exceptions for negative numbers. For example, try adding 0xFFFFFFFF
(-1) and 1
. Since there is only room for 32 bits, this will overflow and the result will be 0
as expected.
更多信息请访问:
http://en.wikipedia.org/wiki/Two%27s_complement
这篇关于波浪号çVS无符号整数签署的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!