Boolean operators vs Bitwise operators

前端 未结 9 1230
孤街浪徒
孤街浪徒 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:28

    Logical Operations

    are usually used for conditional statements. For example:

    if a==2 and b>10:
        # Do something ...
    

    It means if both conditions (a==2 and b>10) are true at the same time then the conditional statement body can be executed.

    Bitwise Operations

    are used for data manipulation and extraction. For example, if you want to extract the four LSB (Least Significant Bits) of an integer, you can do this:

    p & 0xF
    
    0 讨论(0)
  • 2020-11-22 07:29

    Here are a couple of guidelines:

    • Boolean operators are usually used on boolean values but bitwise operators are usually used on integer values.
    • Boolean operators are short-circuiting but bitwise operators are not short-circuiting.

    The short-circuiting behaviour is useful in expressions like this:

    if x is not None and x.foo == 42:
        # ...
    

    This would not work correctly with the bitwise & operator because both sides would always be evaluated, giving AttributeError: 'NoneType' object has no attribute 'foo'. When you use the boolean andoperator the second expression is not evaluated when the first is False. Similarly or does not evaluate the second argument if the first is True.

    0 讨论(0)
  • 2020-11-22 07:31

    Here's a further difference, which had me puzzled for a while just now: because & (and other bitwise operators) have a higher precedence than and (and other boolean operators) the following expressions evaluate to different values:

    0 < 1 & 0 < 2
    

    versus

    0 < 1 and 0 < 2
    

    To wit, the first yields False as it is equivalent to 0 < (1 & 0) < 2, hence 0 < 0 < 2, hence 0 < 0 and 0 < 2.

    0 讨论(0)
提交回复
热议问题