C语言 当我为 unsigned int 分配负值时会发生什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7152759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What happens when I assign a negative value to an unsigned int?
提问by n0nChun
Possible Duplicate:
signed to unsigned conversion in C - is it always safe?
可能的重复:
C 中的有符号到无符号转换 - 它总是安全的吗?
Let's say I declare a variable of type unsigned int : unsigned int x = -1;
假设我声明了一个 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?
现在,二进制补码中的 -1(假设是 32 位机器)是 0xFFFFFFFF。现在,当我将此值分配给 x 时,是否将值 0x7FFFFFFF 分配给了 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?
如果是这样,则 printf ("%d",x); 会打印 0x7FFFFFFF 的十进制等效值,对吗?但是,显然这不会发生,因为打印的值是 -1。我在这里缺少什么?
Edit: I know that we can use the %u format specifier to print unsigned values. But that doesn't help answer the question above.
编辑:我知道我们可以使用 %u 格式说明符打印无符号值。但这无助于回答上述问题。
回答by Keith Thompson
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 %xto see it in hexadecimal.
该"%d"格式是(signed)int的值。如果将它与无符号值一起使用,它可能会打印实际值以外的内容。使用"%u"看实际值,或者%x看到它在十六进制。
In the declaration
在声明中
unsigned int x = -1;
the expression -1is 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 modulo UINT_MAX + 1, so -1will convert to UINT_MAX(which is probably 0xffffffffor 4294967295if unsigned intis 32 bits).
表达式-1的类型为 int,值为 -1。初始化程序将此值从 int 转换为 unsigned int。有符号到无符号转换的规则说该值是模减少的UINT_MAX + 1,因此-1将转换为UINT_MAX(可能是0xffffffff或4294967295如果unsigned int是 32 位)。
You simply cannotassign 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.
您根本无法为无符号类型的对象分配负值。任何这样的值在分配之前都会被转换为无符号类型,并且结果总是 >= 0。
回答by Eran Zimmerman
Use %uinstead of %din order to print unsigned values. Then you should see 0xFFFFFFFF.
使用%u而不是%d为了打印无符号值。然后你应该看到 0xFFFFFFFF。
回答by Rickard
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.
发生的事情是您首先将值转换为 unsigned int,将 0xffffffff 分配给 x。然后使用 printf("%d\n") 将值转换回有符号 int 仍然保持 0xffffffff 的值。因此打印-1。

