Bit masking in Python

前端 未结 4 958
臣服心动
臣服心动 2021-02-14 04:11

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

4条回答
  •  没有蜡笔的小新
    2021-02-14 04:39

    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):
        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')
    

提交回复
热议问题