Search code examples
python-3.xbit-manipulationbit

Check whether a specific bit is set in Python 3


I have two bytes in:

b'T' 

and

b'\x40'     (only bit #6 is set)

In need to perform a check on the first byte to see if bit # 6 is set. For example, on [A-Za-9] it would be set, but on all some characters it would not be set.

if (b'T' & b'\x40') != 0:
    print("set");

does not work ...


Solution

  • Byte values, when indexed, give integer values. Use that to your advantage:

    value = b'T'
    if value[0] & 0x40:
        print('set')
    

    You cannot use the & operator on bytes, but it works just fine on integers.

    See the documentation on the bytes type:

    While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that 0 <= x < 256[.]

    Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b, b[0] will be an integer[.]

    Note that non-zero numbers always test as true in a boolean context, there is no need to explicitly test for != 0 here either.