The Python Oracle

python check if bit in sequence is true or false

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: The World Wide Mind

--

Chapters
00:00 Python Check If Bit In Sequence Is True Or False
00:18 Answer 1 Score 4
00:25 Answer 2 Score 5
00:34 Accepted Answer Score 23
01:02 Answer 4 Score 2
01:07 Thank you

--

Full question
https://stackoverflow.com/questions/2859...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #bit

#avk47



ACCEPTED ANSWER

Score 23


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.




ANSWER 2

Score 5


You can use bit shifting

>>> 0b10010101 >> 4 & 1
1
>>> 0b10010101 >> 3 & 1
0



ANSWER 3

Score 4


bits = 0b11010011

if bits & (1 << 3):
    ...



ANSWER 4

Score 2


bits = '1110111'

if bits[-4] == '0':
    print "......false"
else:
    print  "....true"