Boolean operators vs Bitwise operators

前端 未结 9 1414
孤街浪徒
孤街浪徒 2020-11-22 06:34

I am confused as to when I should use Boolean vs bitwise operators

  • and vs &
  • or vs |
9条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 07:13

    The hint is in the name:

    • Boolean operators are for performing logical operations (truth testing common in programming and formal logic)
    • Bitwise operators are for "bit-twiddling" (low level manipulation of bits in byte and numeric data types)

    While it is possible and indeed sometimes desirable (typically for efficiency reasons) to perform logical operations with bitwise operators, you should generally avoid them for such purposes to prevent subtle bugs and unwanted side effects.

    If you need to manipulate bits, then the bitwise operators are purpose built. The fun book: Hackers Delight contains some cool and genuinely useful examples of what can be achieved with bit-twiddling.

提交回复
热议问题