How can I determine if overflow occured using AND OR NOT and XOR?

后端 未结 3 991
甜味超标
甜味超标 2021-01-25 12:02

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 wi

3条回答
  •  悲哀的现实
    2021-01-25 12:54

    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 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))
    

    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: I assumed that the sum was available in another variable which the other answers didn't assume

提交回复
热议问题