Skip to content Skip to sidebar Skip to footer

Bit Masking In Python

I have a byte (from some other vendor) where the potential bit masks are as follows: value1 = 0x01 value2 = 0x02 value3 = 0x03 value4 = 0x04 value5 = 0x05 value6 = 0x06 value7 = 0x

Solution 1:

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 = 0x07
mask1 = 0x40
mask2 = 0x80

Now your function becomes

def parse_byte(byte):
    returnbyte & 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')

Solution 2:

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 inrange(6))>>>bdict[x & 0b00111111]
4

Solution 3:

You don't need the other two functions:

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

Solution 4:

It's a little verbose but perfectly fine. The only change I'd make is to simplify parse_byte:

def parse_byte(byte):

     value7_set = byte & value7 == value7value8_set=byte & value8 == value8base_value= mask_bits_on_byte(byte,value7 | value8)
     return value7_set,value8_set,base_value  

Post a Comment for "Bit Masking In Python"