如何使用AND OR NOT和XOR确定是否发生溢出? [英] How can I determine if overflow occured using AND OR NOT and XOR?

查看:169
本文介绍了如何使用AND OR NOT和XOR确定是否发生溢出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试仅使用AND或XOR,而不是确定是否将2个二进制数(由4位组成)相加是否溢出. 例如,我知道1100 + 0100会变成1 | 0000.但是我如何仅使用这些逻辑运算符来找到它?

I'm trying to use only AND OR XOR and NOT to determine whether adding 2 binary number made of 4 bits will overflow. I know, for example, that something like 1100 + 0100 will wind up as 1 | 0000. But how can I find this using just these logical operators?

当溢出发生时,我试图获得1000,而当溢出发生时,我试图获得0000.这很容易,因为我可以将XOR与掩码一起使用以清除最后3位.

I'm trying to get 1000 when overflow happens, and 0000 when it doesn't. This is easy enough since I can just use XOR with a mask to clear the last 3 bits.

有人建议解决这个问题吗?

Does anyone have suggestions for figuring this out?

推荐答案

在过去的几天里,我一直停留在同一个问题上,并找出了答案.假设有两个4位数字a,b,并且它们的和存储在另一个4位数字s中,那么当第一位紧随其后时出现溢出

I was stuck on the same question for the past few days and figured out the answer. Assuming there are two 4-bit numbers a, b and their sum stored in another 4-bit number s, there is an overflow when the first bits are following

a = 0, b = 0, s = 1
a = 1, b = 1, s = 0

(NOT a)AND(NOT b)AND s对于第一种溢出情况返回1 对于第二种情况,a AND b AND(NOT s)返回1.您可以对它们进行OR运算,以将1作为结果的第一位.所以,

(NOT a) AND (NOT b) AND s returns 1 for the first case of overflow a AND b AND (NOT s) returns 1 for the second case. You can OR them for getting 1 as the first bit of the result. So,

((NOT a) AND (NOT b) AND s) OR (a AND b AND (NOT s))

如果发生溢出,

表达式将返回1xxx.将上面的表达式与1000进行与"运算将在发生溢出时返回1000,而在没有发生溢出时则返回0000.因此,最终答案是:

expression returns 1xxx in case of overflow. ANDing the above expression with 1000 returns 1000 when there is an overflow and 0000 when there is no overflow. So, final answer is:

(((NOT a) AND (NOT b) AND s) OR (a AND b AND (NOT s))) AND 1000

PS:我假设总和在另一个变量未假定的另一个变量中可用

PS: I assumed that the sum was available in another variable which the other answers didn't assume

这篇关于如何使用AND OR NOT和XOR确定是否发生溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆