Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python check if bit in sequence is true or false

Tags:

python

bits

I want to find if a bit in a sequense is 1 or 0 (true or false) if i have some bitsequense of 11010011, how can i check if the 4th position is True or False?

example:

10010101 (4th bit) -> False
10010101 (3rd bit) -> True
like image 544
Hans de Jong Avatar asked Feb 18 '15 18:02

Hans de Jong


4 Answers

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.

like image 96
Andrea Corbellini Avatar answered Oct 13 '22 01:10

Andrea Corbellini


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)
like image 32
kjp Avatar answered Oct 13 '22 00:10

kjp


You can use bit shifting

>>> 0b10010101 >> 4 & 1
1
>>> 0b10010101 >> 3 & 1
0
like image 40
Cory Kramer Avatar answered Oct 13 '22 01:10

Cory Kramer


bits = 0b11010011

if bits & (1 << 3):
    ...
like image 36
John Kugelman Avatar answered Oct 12 '22 23:10

John Kugelman