Are shifts allowed as bitwise operators? Are arithmetic operations allowed?
Your editing is not entirely clear, but I assume you need to implement the equivalent
a ? b : c
where a , b and c are integers. This in turn is equivalent to
a != 0 ? b : c
One way to achieve this is to find a way to turn the non-zero value of a into a pattern with bits of the same type using only bitwise operators. If we figure out how to do this, the rest will be easy. Now I don’t immediately remember some ingenious tricks that will do this (they exist, I think), and I don’t know exactly which operators are allowed and which are not, so at the moment I'm just using something like
a |= a >> 1; a |= a >> 2; a |= a >> 4; a |= a >> 8; a |= a >> 16; a |= a << 1; a |= a << 2; a |= a << 4; a |= a << 8; a |= a << 16;
For a 32-bit integer type, if (and only if) at least one bit was set in the original a , then the above should result in all bits of a being set to 1. (Assume that we work with unsigned integers to avoid problems associated with the transfer of signed values). Again, there must be a smarter way to do this, I'm sure. For example: a = !a - 1 , but I don’t know if ! and - .
Once we have done this, the original conditional statement becomes equivalent
(a & b) | (~a & c)
Done.
source share