C 中的无符号和有符号值(输出) [英] Unsigned and Signed Values in C (Output)
问题描述
signed int x = -5;
unsigned int y = x;
y
的值是多少?这是怎么回事?
What is the value of y
? How is this so?
推荐答案
取决于unsigned int
的最大值.通常,unsigned int
是 32 位长,所以 UINT_MAX
是 232 −1. C 标准 (§6.3.1.3/2) 需要签名的 →无符号转换执行为
It depends on the maximum value of the unsigned int
. Typically, a unsigned int
is 32-bit long, so the UINT_MAX
is 232 − 1. The C standard (§6.3.1.3/2) requires a signed → unsigned conversion be performed as
否则,如果新类型是无符号的,则通过重复加或减一个新类型可以表示的最大值来转换该值,直到该值在新类型的范围内.
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
因此 y = x + ((232 − 1) + 1) = 232 −5 = 4294967291.
Thus y = x + ((232 − 1) + 1) = 232 − 5 = 4294967291.
在 2 的补充平台中,现在大多数实现是,y
也与 x
的 2 的补码表示相同.
In a 2's complement platform, which most implementations are nowadays, y
is also the same as 2's complement representation of x
.
-5 = ~5 + 1 = 0xFFFFFFFA + 1 = 0xFFFFFFFB = 4294967291.
-5 = ~5 + 1 = 0xFFFFFFFA + 1 = 0xFFFFFFFB = 4294967291.
这篇关于C 中的无符号和有符号值(输出)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!