Why is (a | b ) equivalent to a - (a & b) + b?

前端 未结 4 1443
孤城傲影
孤城傲影 2021-02-04 03:26

I was looking for a way to do a BITOR() with an Oracle database and came across a suggestion to just use BITAND() instead, replacing BITOR(a,b) with a + b - BITAND(a,b).

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-04 04:09

    A & B is the set of bits that are on in both A and B. A - (A & B) leaves you with all those bits that are only on in A. Add B to that, and you get all the bits that are on in A or those that are on in B.

    Simple addition of A and B won't work because of carrying where both have a 1 bit. By removing the bits common to A and B first, we know that (A-(A&B)) will have no bits in common with B, so adding them together is guaranteed not to produce a carry.

提交回复
热议问题