Search code examples
mathlogicbit-manipulationbitwise-operators

Is there a way to use Bitwise Operators instead of multiple Ternary Operators?


Is there a way to get a result of applying a ternary ?: operator to individual bits without actually computing it one bit at a time, i.e. using some combination of and-s, or-s, xor-s, and not-s?

In other words, given we have 3 ints (regardless of bit length): a, b, and mask m, the result r should basically be: r = m ? a : b, except on a per-bit basis.

Assuming a = 0b0101; b = 0b1110; and m = 0b0110, the result r should be 0b1100. So, if bit n in mask m is 1 (true), use the n-th bit from a; otherwise (if bit n in mask m is 0 (false)) then use the n-th bit from b.


Solution

  • If m, a and b are all guaranteed to be 0 or 1, then m ? a : b is equivalent to (m && a) || (!m && b). You can see that by injecting m=0 or m=1 in the formula and simplifying it.

    This works bitwise too; bitwise not is usually noted ~; so the "bitwise ternary operator" that you are looking for can be expressed as:

    (m&a)|((~m)&b)