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

∥☆過路亽.° 提交于 2020-06-09 04:07:26

问题


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?

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?


回答1:


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.




回答2:


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




回答3:


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
}


来源:https://stackoverflow.com/questions/4805924/how-can-i-determine-if-overflow-occured-using-and-or-not-and-xor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!