标题党标题党
最近在CSAPP看到一个有趣的小例子 -1== 4294967295?
先上代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #include<iostream> #include<bitset> #include<stdlib.h> #include<bits/stdc++.h> using namespace std; int main() { int x=-8; int y=7; unsigned ux=x; unsigned uy=y; std::cout<<x+y<<std::endl; std::cout<<ux+uy<<std::endl; }
|
然后此时我们比较
1 2
| bool judge=((x+y)==(ux+uy)?ture:false); std::cout<<judge<<std::endl;
|
-1==4294967295? 这肯定不相等啊
结果是
查看一下两个数的二进制
1 2
| std::cout<<"二进制 "<<bitset<32>(x+y)<<std::endl; std::cout<<"二进制 "<<bitset<32>(ux+uy)<<std::endl;
|
结果是
1 2
| 11111111111111111111111111111111 11111111111111111111111111111111
|
二进制表示完全相等,难道 == 符号比较两个数是否相等是比较他们的二进制表示是否完全相等?
不止是 == 符号 如果一个运算数是有符号的而另一个又是无符号的,C语言会隐式地将有符号参数强制类型转换为无符号数(好像大家都知道了)
>符号
1 2 3 4 5 6 7 8 9 10 11 12
| #include<iostream> #include<bitset> #include<stdlib.h> #include<bits/stdc++.h> using namespace std; int main() { int x=-1; unsigned u=2; bool judge=((x>u)?true:false); std::cout<<judge; }
|
结果为True,x处理为无符号数远大于2
结:补码和无符号加法有相同的位级行为,而且是可交换的