Bit masking in Python

前端 未结 4 883
臣服心动
臣服心动 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:38

    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
    
    0 讨论(0)
  • 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')
    
    0 讨论(0)
  • 2021-02-14 04:57

    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
    
    0 讨论(0)
  • 2021-02-14 04:58

    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 == value7
         value8_set = byte & value8 == value8
         base_value = mask_bits_on_byte(byte,value7 | value8)
         return value7_set,value8_set,base_value  
    
    0 讨论(0)
提交回复
热议问题