Getting a specific bit value in a byte string

Posted by ignoramus on Stack Overflow See other posts from Stack Overflow or by ignoramus
Published on 2010-04-07T10:06:30Z Indexed on 2010/04/07 10:13 UTC
Read the original article Hit count: 270

Filed under:
|
|

There is a byte at a specific index in a byte string which represents eight flags; one flag per bit in the byte. If a flag is set, its corresponding bit is 1, otherwise its 0. For example, if I've got

b'\x21'

the flags would be

0001 0101    # Three flags are set at indexes 3, 5 and 7
             # and the others are not set

What would be the best way to get each bit value in that byte, so I know whether a particular flag is set or not? (Preferably using bitwise operations)

© Stack Overflow or respective owner

Related posts about python

Related posts about bytes