百度: 补码
wiki: Two's complement
整数的补码 two's complement of an signed integer
分数的补码 tow's complement of a fractional number
原码
原码(true form)是一种计算机中对数字的二进制定点表示方法。原码表示法在数值前面加了一位符号位(即最高位为符号位)
: 正数该位为0,负数该位为1(0有两种表示:+0和-0),其余位表示数值的大小。
7: 0000 1011
-7: 1000 1011
补码(two's complement)
1、在计算机系统中,数值一律用补码来表示(存储)。 主要原因:使用补码,可以将符号位和其它位统一处理;
同时,减法也可按加法来处理。另外,两个用补 码表示的数相加时,如果最高位(符号位)有进位,则进位被舍弃。
2、补码与原码的转换过程几乎是相同的。
正数的补码
与原码相同
7 = 0000 1011
char a = 7; // 查看内存: 0x07
负数的补码
负数的补码是对其原码逐位取反,但符号位除外;然后整个数加1。
-7: 1000 1011 (原) 1111 0100(反) 1111 0101(补)
之所以取补,是因为由于符号不能参与运算,取补之后,符号位就能参与运算了。
"什么叫补?" -- 补就是补充的意思, 定义本码为去掉符号位的绝对值
本码 + 补码 = 2^ (N+1)
例如: 0000 1011 (-7) + 1111 0101 = 1 0000 0000
所以,负数补码的速算法 : 2^ (N+1) - 绝对值
例如: -7的补码 = 256 - 7 = 1 0000 0000 - 0000 1011
char a = -7; // 查看内存: 0xF9 ,验算一下0xF9 - 0x100 = -0x07
任意N位补码的真值(整数)计算
先按正整数计算出S
首位为0: 该整数是正数
S' = S
首位为1: 该整数是负数
S' = S - 2^(N+1)
任意N位补码的真值(分数)计算
分数也可以用2进制表示, 先按整数算出去分子的真值F
然后 F' = F / 2^N
例如:
正分数 0 0110 (补)
分子 = 0110 = 6
分母 = 2^5 = 16
F' = 6/16
负分数 1 1010 (补)
分子 = 1 1010 - 10 0000 = 1010 - 1 0000 = 10 - 16 = -6
分母 = 16
F' = -6/16
举例:
http://www.swarthmore.edu/NatSci/echeeve1/Ref/BinaryMath/NumSys.html
Convert 0.100 1001 to decimal. 正分数 2进制 -> 10进制
Take the binary number 0100 1001 (=73), and divide by 27=128. The answer is 73/128=0.5703125, which agrees with the result of the
previous exercise (Positive Binary Fractions).
Convert 1.100 1001 to decimal. 负分数 2进制 -> 10进制
Take the two's complements binary number 1100 1001 (=-55), and divide by 128. The answer is -0.4296875, which agrees with the result
of the previous exercise (Signed Binary Fractions).
Convert 0.9 to Q7 format
Multiply 0.9 by 128 to get 115.2. This is represented in binary as 111 0011, so the Q7 representation is 0.111 0011. This agrees with the result of the previous exercise (Positive Binary Fractions).
Convert -0.9 to Q7 format
Multiply -0.9 by 128 to get -115.2. The Q7 representation is 1.000 1101. This agrees with the result of the previous exercise (Signed Binary Fractions).