且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用AND OR NOT和XOR确定是否发生溢出?

更新时间:2023-02-22 13:17:57

在过去的几天里,我一直停留在同一个问题上,并找出了答案.假设有两个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