Bit masking in Python

前端 未结 4 885
臣服心动
臣服心动 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<>> bdict[x & 0b00111111]
    4
    

提交回复
热议问题