Boolean operators vs Bitwise operators

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

    Boolean operation are logical operations.

    Bitwise operations are operations on binary bits.

    Bitwise operations:

    >>> k = 1
    >>> z = 3
    >>> k & z  
    1
    >>> k | z  
    3
    

    The operations:

    • AND &: 1 if both bits are 1, otherwise 0
    • OR |: 1 if either bit is 1, otherwise 0
    • XOR ^: 1 if the bits are different, 0 if they're the same
    • NOT ~': Flip each bit

    Some of the uses of bitwise operations:

    1. Setting and Clearing Bits

    Boolean operations:

    >>> k = True
    >>> z = False
    >>> k & z  # and
    False
    >>> k | z  # or
    True
    >>> 
    

提交回复
热议问题