Bit masking in Python Bit masking in Python python python

Bit masking in Python


Most of your value* constants aren't actually bit masks, only value7 and value8 are. I'd define another bit mask to extract the lower bits, so I would have three bit masks in total:

mask0 = 0x07mask1 = 0x40mask2 = 0x80

Now your function becomes

def parse_byte(byte):    return byte & mask2, byte & mask1, byte & mask0

I did not convert the results to bool -- I don't see why this should be necessary. When checking the returned value with if, it will be implicitly converted to bool anyway.

Also note that

format(value,'b').zfill(8)

can be simplified to

format(value,'08b')


Given a value such as:

>>> x = 0b10001000

You can find out whether the top bits are set with:

>>> bit8 = bool(x & 0b10000000)>>> bit7 = bool(x & 0b01000000)

To find which lower bit is set, use a dictionary:

>>> bdict = dict((1<<i, i+1) for i in range(6))>>> bdict[x & 0b00111111]4


You don't need the other two functions:

def parse_byte(byte):    value7_set = byte & value7 == value7    value8_set = byte & value8 == value8    base_value =  byte & 7    return value7_set,value8_set,base_value