python check if bit in sequence is true or false
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Book End
--
Chapters
00:00 Question
00:29 Accepted answer (Score 22)
01:06 Answer 2 (Score 11)
01:25 Answer 3 (Score 5)
01:38 Answer 4 (Score 4)
01:48 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
    --
Music by Eric Matyas
https://www.soundimage.org
Track title: Book End
--
Chapters
00:00 Question
00:29 Accepted answer (Score 22)
01:06 Answer 2 (Score 11)
01:25 Answer 3 (Score 5)
01:38 Answer 4 (Score 4)
01:48 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"