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

前端 未结 5 1522
没有蜡笔的小新
没有蜡笔的小新 2021-02-20 17:52

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:36

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

提交回复
热议问题