加减补码 [英] Adding and subtracting two's complement
问题描述
使用六位 1 和 2 的补码表示我试图解决以下问题:
Using six-bit one's and two's complement representation I am trying to solve the following problem:
12 - 7
现在,我先取二进制的 12 和二进制的 7.
Now, i take 12 in binary and 7 in binary first.
12 = 001100 - 6 bit
7 = 000111 - 6 bit
那么,我是否会翻转二进制补码的位并加一个?
Then, would I then flip the bit for two's complement and add one?
12 = 110011 ones complement
+ 1
-------
001101
7 = 111000 ones complement
+ 1
---------
111001
然后,将这两个补码相加
then, add those two complement together
001101
+111001
-------
1000110 = overflow? discard the last digit? If so I get 5
现在,如果我有类似的数字
Now, if I have a number like
-15 + 2
如果 MSB 为零,我会在 MSB 上添加一个符号幅度?
I would then add a sign magnitude on the MSB if it's a zero?
喜欢:
-15 = 001111 6 bit
在我翻转位之前我会在最后添加一个 1 吗?
Would I add a 1 at the end here before I flip the bits?
= 101111
推荐答案
用补码表示负数的好处是减法和加法是一样的.在您的情况下,您可以将 12 - 7
视为 12 + (-7)
.因此,您只需要找到 -7 的二进制补码表示并将其添加到 +12:
Using two's complement to represent negative values has the benefit that subtraction and addition are the same. In your case, you can think of 12 - 7
as 12 + (-7)
. Hence you only need to find the two's complement representation of -7 and add it to +12:
12 001100
-7 111001 -- to get this, invert all bits of 7 (000111) and add 1
----------
5 1000101
然后丢弃进位(表示溢出),得到结果:000101
,如预期的那样等于 5.
Then discard the carry (indicates overflow), and you have your result: 000101
which equals to 5 as expected.
对于您的 -15 + 2
示例,只需按照相同的过程即可获得 -15 的二进制补码表示:
For your example of -15 + 2
, simply follow the same procedure to get the two's complement representation of -15:
15 001111
110000 -- inverted bits
110001 -- add 1
现在像往常一样添加:
-15 110001
2 000010
-----------
res 110011
要看到 res
确实等于 -13,您可以看到它是负数(MSB 集).对于幅度,转换为正数(反转位,加 1):
To see that res
indeed equals -13, you can see that it is negative (MSB set). For the magnitude, convert to positive (invert bits, add 1):
res 110011
001100 -- inverted bits
001101 -- add 1
因此,如预期的那样,震级为 13.
Hence the magnitude is 13 as expected.
这篇关于加减补码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!