Search code examples
bit-manipulationbitwise-operatorsbitwise-andbitwise-or

Is a bitwise OR and AND NOT the same as addition and subtraction when a set is known?


If a = 2 and b = 4 where a OR b = 6 and (a|b) AND NOT b = a then is a bitwise AND NOT equivalent to subtraction when the the value is a set of flags which is known to include the flag being removed?

Is it the same for addition as well?

Note that this is in a situation where the flags are known to exist in the set. No addition or subtraction would occur if the flag is not present.


Solution

  • If I understood correctly what you're asking, yes. So:

    • If (a & b) == 0, then (a | b) == (a + b), and
    • If (a | b) == a, then (a & ~b) == (a - b)

    As a sort of proof, take that addition can be written as a + b == (a ^ b) + ((a & b) << 1) (which is doing all the sums-without-carry, and then adding the carries separately). So if a & b is zero, the carries disappear and it becomes just a ^ b, and that in turn becomes a | b. A similar thing happens with the subtraction where we know there are no borrows.