减去两个未知位大小的值
我正在尝试使用二进制补码将两个值相减。我遇到了溢出位的问题。由于我的容器保存无限位大小的整数,因此我不知道结果的最高位是否确实来自结果或只是溢出。如何在不使用 -
的情况下摆脱溢出(我不能只执行 1 << bits - 1
因为这将涉及使用容器,该容器具有还没有工作operator-
)
0b1111011111 - 0b111010000 -> 0b1111011111 + 0b000110000 -> 1000001111
与(通常)
0b00000101 - 0b000000001 -> 0b00000101 + 0b11111111 -> 0b100000100-> 0b00000100
I'm trying to subtract two values from each other using twos compliment. I have a problem with the overflowing bit. Since my container hold an unlimited bit sized integer, I don't know if the top bit of the result is really from the result or just the overflow. How would I get rid of the overflow without using -
(I can't just do 1 << bits - 1
since that would involve using the container, which has no working operator-
yet)
0b1111011111 - 0b111010000 -> 0b1111011111 + 0b000110000 -> 1000001111
vs (normally)
0b00000101 - 0b000000001 -> 0b00000101 + 0b11111111 -> 0b100000100 -> 0b00000100
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的问题是您要从 10 位
1111011111
中减去 9 位111010000
。111010000
的补码是...11111000110000
,其中的点试图表明您必须向左填充尽可能多的1
根据您需要的位。这里,您需要 10 位,因此111010000
的二进制补码不是000110000
而是1000110000
。因此,您想要计算
1111011111 + 1000110000 = 11000001111
,只需将其截断为 10 位即可得到正确答案1000001111
。Your problem is that you are subtracting the 9-bit
111010000
from the 10-bit1111011111
. The two's complement of111010000
is...11111000110000
, where the dots are trying to show that you have to pad to the left with as many1
bits as you need. Here, you need 10 bits, so the two's complement of111010000
is not000110000
but1000110000
.So you want to calculate
1111011111 + 1000110000 = 11000001111
, which you just truncate to 10 bits to get the correct answer1000001111
.如果你计算 a - b,你必须以某种方式“排列”这个词 - 因为你必须用 m=max(bitwidth(a), bitwidth(b)) 的位宽来对 2 进行补语。
要消除溢出,只需执行 mask = negate(1 << m) ,然后使用按位与应用掩码。
(或者您可以只检查该位并进行相应处理)。
If you calculate a - b you must somehow "arrange" the word - as you have to make for the 2 compliment a negation with the bitwidth of m=max(bitwidth(a), bitwidth(b)).
To get rid of the of overflow you just do mask = negate(1 << m), and apply the mask with bitwise and.
(Or you could just check that bit and treat it accordingly).