二进制补码的加法和减法
使用六位一和二的补码表示法,我试图解决以下问题:
12 - 7
现在,我首先取二进制中的 12 和二进制中的 7。
12 = 001100 - 6 bit
7 = 000111 - 6 bit
然后,我会翻转二进制补码的位并加一吗?
12 = 110011 ones complement
+ 1
-------
001101
7 = 111000 ones complement
+ 1
---------
111001
然后,将这两个补码相加
001101
+111001
-------
1000110 = overflow? discard the last digit? If so I get 5
现在,如果我有一个像这样的数字,
-15 + 2
那么如果它是零,我会在 MSB 上添加一个符号大小?
比如:
-15 = 001111 6 bit
在翻转这些位之前,我会在末尾添加一个 1 吗?
= 101111
Using six-bit one's and two's complement representation I am trying to solve the following problem:
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
I would then add a sign magnitude on the MSB if it's a zero?
like:
-15 = 001111 6 bit
Would I add a 1 at the end here before I flip the bits?
= 101111
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用补码来表示负值的好处是减法和加法是相同的。对于您的情况,您可以将
12 - 7
视为12 + (-7)
。因此,您只需找到 -7 的二进制补码表示并将其与 +12 相加:然后丢弃进位(表示溢出),您就得到结果:
000101
,它等于预期的 5。对于
-15 + 2
的示例,只需按照相同的过程即可获得 -15 的二进制补码表示形式:现在照常进行加法:
确实可以看到
res
等于-13,你可以看到它是负数(MSB设置)。对于幅度,转换为正数(反转位,加 1):因此幅度为预期的 13。
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
as12 + (-7)
. Hence you only need to find the two's complement representation of -7 and add it to +12:Then discard the carry (indicates overflow), and you have your result:
000101
which equals to 5 as expected.For your example of
-15 + 2
, simply follow the same procedure to get the two's complement representation of -15:Now do the addition as usual:
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):Hence the magnitude is 13 as expected.
不会。二进制补码的算法不会根据负值的位置而改变。
No. The algorithm for two's complement doesn't change based on where the negative value is.