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

后端 未结 3 956
甜味超标
甜味超标 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:47

    Numbers are ABCD and EFGH, ^ is AND, | is OR.

    (A^E) | (B^F^(A|E)) | (C^G^(B|F)^(A|E)) | (D^H^(C|G)^(B|F)^(A|E))

    I'm sure you can see the pattern there, so a recursive solution is pretty easy for numbers with more bits.

    0 讨论(0)
  • 2021-01-25 12:52

    I think this will work, using no loops or shifts. But its ugly:

    if (
    (a & 0x8) && (b & 0x8) || 
    (((a & 0x8) || (b & 0x8)) && ((a & 0x4) && (b & 0x4))) ||
    (((a & 0x8) || (b & 0x8)) && ((a & 0x4) || (b & 0x4)) && ((a & 0x2) && (b & 0x2))) ||
    (((a & 0x8) || (b & 0x8)) && ((a & 0x4) || (b & 0x4)) && ((a & 0x2) || (b & 0x2)) && ((a & 0x1) && (b & 0x1)))
    ) {
      // overflow
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题