'(unsigned)1'和'(unsigned)〜0'之间的差异

'(unsigned)1'和'(unsigned)〜0'之间的差异

问题描述:

(无符号)〜0 (无符号)1 有什么区别.为什么〜0 unsigned -1 ,而 1 unsigned 是 1 ?它与无符号数字存储在内存中的方式有​​关吗?为什么未签名的数字会给出签名的结果.它也没有给出任何溢出错误.我正在使用 GCC 编译器:

What is the difference between (unsigned)~0 and (unsigned)1. Why is unsigned of ~0 is -1 and unsigned of 1 is 1? Does it have something to do with the way unsigned numbers are stored in the memory. Why does an unsigned number give a signed result. It didn't give any overflow error either. I am using GCC compiler:

#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
}

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

Because %d is a signed int specifier. Use %u.

在我的机器上打印 4294967295 .

就像其他人提到的那样,如果将最高的无符号值解释为有符号,则得到-1,请参见Wikipedia条目中的二进制补码.

As others mentioned, if you interpret the highest unsigned value as signed, you get -1, see the wikipedia entry for two's complement.