Boolean operators vs Bitwise operators

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

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

  • and vs &
  • or vs |
9条回答
  •  -上瘾入骨i
    2020-11-22 07:19

    The general rule is to use the appropriate operator for the existing operands. Use boolean (logical) operators with boolean operands, and bitwise operators with (wider) integral operands (note: False is equivalent to 0, and True to 1). The only "tricky" scenario is applying boolean operators to non boolean operands.
    Let's take a simple example, as described in [SO]: Python - Differences between 'and' and '&':
    5 & 7 vs. 5 and 7.

    For the bitwise and (&), things are pretty straightforward:

    5     = 0b101
    7     = 0b111
    -----------------
    5 & 7 = 0b101 = 5
    

    For the logical and, here's what [Python.Docs]: Boolean operations states (emphasis is mine):

    (Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument.

    Example:

    >>> 5 and 7
    7
    >>> 7 and 5
    5
    

    Of course, the same applies for | vs. or.

提交回复
热议问题