2

(unsigned)~0和有什么区别(unsigned)1。为什么是unsignedof ~0is-1unsignedof 1is 1?它是否与无符号数字在内存中的存储方式有关。为什么无符号数会给出有符号结果。它也没有给出任何溢出错误。我正在使用 GCC编译器:

#include<sdio.h>
main()
{
 unsigned int x=(unsigned)~0; 
 unsigned int y=(unsigned)1; 
 printf("%d\n",x); //prints -1
 printf("%d\n",y); //prints 1
}
4

4 回答 4

6

因为%d是有符号的 int 说明符。使用%u.

4294967295在我的机器上打印。

正如其他人所提到的,如果您将最高的无符号值解释为有符号,您会得到 -1,请参阅 wikipedia entry for two's complement

于 2013-09-30T01:23:30.293 回答
2

您的系统使用负数的二进制补码表示。在此表示中,由全为 1 的二进制数表示最大的负数-1

由于反转零的所有位会为您提供一个由所有 1 组成的数字,因此-1当您通过打印它来将数字重新解释为有符号数字时,您会得到一个%d需要有符号数字而不是无符号数字的数字。

于 2013-09-30T01:24:01.243 回答
1

First, in your use of printf you are telling it to print the number as signed ("%d") instead of unsigned ("%u").

Second, you are right in that it has "something to do with the way numbers are stored in memory". An int (signed or unsigned) is not a single bit on your computer, but a collection of k bits. The exact value of k depends on the specifics of your computer architecture, but most likely you have k=32.

For the sake of succinctness, lets assume your ints are 8 bits long, so k=8 (this is most certainly not the case, unless you are working on a very limited embedded system,). In that case (int)0 is actually 00000000, and (int)~0 (which negates all the bits) is 11111111.

Finally, in two's complement (which is the most common binary representation of signed numbers), 11111111 is actually -1. See http://en.wikipedia.org/wiki/Two's_complement for a description of two's complement.

If you changed your print to use "%u", then it will print a positive integer that represents (2^k-1) where k is the number of bits in an integer (so probably it will print 4294967295).

于 2013-09-30T01:38:09.460 回答
0

printf()只知道您通过您在格式字符串中使用的格式说明符传递了什么类型的变量。所以这里发生的事情是您正在打印xy作为有符号整数,因为您%d在格式字符串中使用了。试试%u吧,你会得到一个更符合你预期的结果。

于 2013-09-30T01:24:48.497 回答