unsigned int + int型结果分析

来源:互联网 发布:显示器支架 知乎 编辑:程序博客网 时间:2024/05/08 00:05

***************************************************

更多精彩,欢迎进入:http://shop115376623.taobao.com

***************************************************


代码如下:

        “//”后为调试中的结果

unsigned int a = 6;  //a = 6                                        【补码:0000   0000   0000   0000   0000   0000   0000   0110】

int b = -20;  //b = -20                                                   【补码:1111   1111   1111   1111   1111   1111   1110   1100】
unsigned int c = a + b;  //c = 4294967282             【补码:1111   1111   1111   1111   1111   1111   1111   0010】

int d = a + b;  //d = -14    

【int d = a + b;  //d = -14:由  《补码:1111   1111   1111   1111   1111   1111   1111   0010》减去1,再取反得到14,保留最高位符号位】

if (a+b>6)
{
printf(">6\n");   //进入此判断,即a+b = c,而非d;

else
{
printf("<=6\n");

}


分析:

机器在数据都是由二进制补码表示的
正数的补码就是其本身
负数的补码是符号位不变各位取反再加一

8位机的话:
int a -1;                      在机器中1111 1111
unsigned int b 1;          在机器中0000 0001

如果 a+b 
a就转化为unsigned int 但里面的数值是不变的 1111 1111 把他转化成十进制2^8-1 + b


0 0
原创粉丝点击