python check if bit in sequence is true or false

Without the bit shifting:

if bits & 0b1000:
    ...

EDIT: Actually, (1 << 3) is optimized out by the compiler.

>>> dis.dis(lambda x: x & (1 << 3))
  1           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               3 (8)
              6 BINARY_AND          
              7 RETURN_VALUE        
>>> dis.dis(lambda x: x & 0b1000)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               1 (8)
              6 BINARY_AND          
              7 RETURN_VALUE    

The two solutions are equivalent, choose the one that looks more readable in your context.


Bitwise left-shifting and bitwise AND operator is your friend. In general you can check if the nth bit is set/unset as below:

if (x & (1<<n)) 
  ## n-th bit is set (1)

else 
  ## n-th bit is not set (0)

Tags:

Python

Bits