Are shifts allowed as bitwise operators? Are arithmetic operators allowed?
Your edit is not entirely clear, but I assume that you need to implement an equivalent of
a ? b : c
where a
, b
and c
are integers. This is in turn equivalent to
a != 0 ? b : c
One way to achieve that is to find a way to turn non-zero value of a
into an all-ones bit pattern using only bitwise operators. If we figure out how to do that, the rest would be easy. Now, I don't immediately remember any ingenious tricks that would do that (they do exist I believe), and I don't know for sure which operators are allowed and which are not, so for now I will just use 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) there was at least one bit set in the original a
, the above should result in all bits of a
set to 1. (Let's assume we are working with unsigned integers, to avoid the issues associated with shifting of signed values). Again,
there must be a more clever way to do that, I'm sure.
(For example: a = !a - 1
but I don't know if !
and -
are allowed.)
Once we've done that, the original conditional operator becomes equivalent to
(a & b) | (~a & c)
Done.