First of all, let me explain that the original code, inverse code and complement code of positive numbers are the same, that is, original code = inverse code = complement code
. So next we mainly talk about the relationship between the original code, inverse code and complement code of negative numbers.
1. Original code
The original code is the sign bit plus the absolute value of the true value, that is, the first bit (highest bit) is used to represent the sign , and the remaining bits represent the value. for example:
1的原码 00000000000000000000000000000001
5的原码 00000000000000000000000000000101
-1的原码 10000000000000000000000000000001
2. Inverse code (for negative numbers)
The inverse code is equal to the sign bit of the original code, and the remaining bits are inverted (that is, 0 becomes 1, 1 becomes 0)
-3 原码 10000000000000000000000000000011
反码 11111111111111111111111111111100
-21 原码 10000000000000000000000000010101
反码 11111111111111111111111111101010
3. Complement (for negative numbers)
Two's complement = one's complement + 1
-3 原码 10000000000000000000000000000011
反码 11111111111111111111111111111100
补码 11111111111111111111111111111101
-21 原码 10000000000000000000000000010101
反码 11111111111111111111111111101010
补码 11111111111111111111111111101011
4. Operation
When the computer performs the calculation, it performs the operation between the complement codes, and finally expresses the result in the original code.
Operations such as 2 + (-5) = -3
2的原码 00000000000000000000000000000010
反码 00000000000000000000000000000010
补码 00000000000000000000000000000010
-5的原码 10000000000000000000000000000101
反码 11111111111111111111111111111010
补码 11111111111111111111111111111011
2+(-5)的运算(补码之间)
00000000000000000000000000000010 (2的补码)
11111111111111111111111111111011 (-5的补码)
结果 11111111111111111111111111111101 (2-5的补码形式)
11111111111111111111111111111100 (2-5的补码-1得到反码)
10000000000000000000000000000011 (2-5的反码符号位不变,其余位取反得到原码)
10000000000000000000000000000011 等于-3(原码表示的就是最终运算结果)