'(unsigned)1'和'(unsigned)〜0'之间的差异 [英] Difference between '(unsigned)1' and '(unsigned)~0'

查看:64
本文介绍了'(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.

这篇关于'(unsigned)1'和'(unsigned)〜0'之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆