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

前端 未结 5 2003
误落风尘
误落风尘 2021-02-20 18:01

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         


        
5条回答
  •  南笙
    南笙 (楼主)
    2021-02-20 18:49

    ~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!

提交回复
热议问题