当我将负值赋给 unsigned int 时会发生什么?
可能的重复:
C 中的有符号到无符号转换 - 它总是安全吗?
假设我声明了一个 unsigned int 类型的变量: unsigned int x = -1;
现在 -1 的二进制补码(假设 32 位机器)是 0xFFFFFFFF。 现在,当我将此值赋给 x 时,值 0x7FFFFFFF 是否被赋给了 x?
如果是这样,则 printf("%d",x);会打印 0x7FFFFFFF 的十进制等值,对吧?但是,显然这不会发生,因为打印的值为 -1。我在这里缺少什么?
编辑:我知道我们可以使用 %u 格式说明符来打印无符号值。 但这无助于回答上面的问题。
Possible Duplicate:
signed to unsigned conversion in C - is it always safe?
Let's say I declare a variable of type unsigned int : unsigned int x = -1;
Now -1 in two's complement (assuming 32 bit machine) is 0xFFFFFFFF.
Now when I assigned this value to x, did the value 0x7FFFFFFF get assigned to x?
If it were so, then printf ("%d",x); would have printed the decimal equivalent of 0x7FFFFFFF, right? But, clearly this isn't happening, as the value that gets printed is -1. What am I missing here?
Edit: I know that we can use the %u format specifier to print unsigned values.
But that doesn't help answer the question above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
"%d"
格式适用于(有符号)int 值。如果将其与无符号值一起使用,它可能会打印实际值以外的内容。使用"%u"
查看实际值,或使用%x
查看十六进制值。在声明中,
表达式
-1
的类型为int,值为-1。初始化器将此值从 int 转换为 unsigned int。有符号到无符号转换的规则规定,该值会以UINT_MAX + 1
为模减少,因此-1
将转换为UINT_MAX
(其中如果unsigned int
是 32 位,则可能是0xffffffff
或4294967295
)。您只是不能将负值赋给无符号类型的对象。任何此类值在分配之前都会被转换为无符号类型,并且结果将始终 >= 0。
The
"%d"
format is for (signed) int values. If you use it with an unsigned value, it could print something other than the actual value. Use"%u"
to see the actual value, or%x
to see it in hexadecimal.In the declaration
the expression
-1
is of type int, and has the value -1. The initializer converts this value from int to unsigned int. The rules for signed-to-unsigned conversion say that the value is reduced moduloUINT_MAX + 1
, so-1
will convert toUINT_MAX
(which is probably0xffffffff
or4294967295
ifunsigned int
is 32 bits).You simply cannot assign a negative value to an object of an unsigned type. Any such value will be converted to the unsigned type before it's assigned, and the result will always be >= 0.
使用
%u
而不是%d
来打印无符号值。然后你应该看到 0xFFFFFFFF。Use
%u
instead of%d
in order to print unsigned values. Then you should see 0xFFFFFFFF.发生的情况是,您首先将值转换为 unsigned int,将 0xffffffff 分配给 x。然后使用 printf("%d\n") 将值转换回有符号 int,仍保留 0xffffffff 值。因此打印-1。
What is happening is that you convert the value first to unsigned int, assigning 0xffffffff to x. Then using printf("%d\n") you will convert the value back to signed int still keeping the value of 0xffffffff. Thus printing -1.