存储在计算机中的数据是一定的,所谓的无符号数,只是对于数据的解读方式不一样,并不影响数据之间的计算。而无符号数之间进行的加减法运算,是通过补码来进行的。比如a - b,实质上是a补 + (-b补)。
for example:
unsigned int x = 5;
unsigned int y = 10;
cout << x - y << endl;
x - y的结果,并不是我们常规计算得到的-5,程序运行的结果如下:
4294967291
--------------------------------
Process exited after 0.3427 seconds with return value 0
请按任意键继续. . .
初看可能很怪异,但是根据我们上面所说的,将这个减法过程手动模拟一下,就可以理解了:
5的原码: 00000000 | 00000000 | 00000000 | 00000101
10的原码:00000000 | 00000000 | 00000000 | 00001010
5的补码: 00000000 | 00000000 | 00000000 | 00000101
-10的补码:11111111 | 11111111 | 11111111 | 11110110
(5)补 + (-10)补 = 00000000 00000000 00000000 00000101 + 11111111 11111111 11111111 11110110
= 11111111 | 11111111 | 11111111 | 11111011
上面的结果如果用无符号整数解读出来应该就是4294967291。我们可以验证一下:
#include<bits/stdc++.h>
using namespace std;
int main(){
unsigned int x = 5;
unsigned int y = 10;
bitset<32> bs(x - y);
cout << bs << endl;
return 0;
}
11111111111111111111111111111011
--------------------------------
Process exited after 0.04406 seconds with return value 0
请按任意键继续. . .
所以,所谓无符号数,只是一种对于数据的解读方式,并不影响数据之间的计算。