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

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

提交回复
热议问题