How could I implement logical implication with bitwise or other efficient code in C?

alvatar picture alvatar · Mar 21, 2009 · Viewed 10.1k times · Source

I want to implement a logical operation that works as efficient as possible. I need this truth table:

p    q    p → q
T    T      T
T    F      F
F    T      T
F    F      T

This, according to wikipedia is called "logical implication"

I've been long trying to figure out how to make this with bitwise operations in C without using conditionals. Maybe someone has got some thoughts about it.

Thanks

Answer

Chris Dolan picture Chris Dolan · Mar 21, 2009
~p | q

For visualization:

perl -e'printf "%x\n", (~0x1100 | 0x1010) & 0x1111'
1011

In tight code, this should be faster than "!p || q" because the latter has a branch, which might cause a stall in the CPU due to a branch prediction error. The bitwise version is deterministic and, as a bonus, can do 32 times as much work in a 32-bit integer than the boolean version!