Search code examples
python-3.xbinaryhexbytedecode

How to convert n most significant bits in a hexadecimal byte string in Python 3


In Python 3, I am using PySerial to read two bytes and I would like to get the decimal representation of the 11 most significant bits in those two bytes.

This is a print of two bytes that I get from my serial communication as an example:

b'\x1e@'

Those two bytes have the following binary representation:

00011110 01000000

I want to keep the 11 most significant bits, here shown without leading zeros:

11110010

And convert the result to a decimal value, or 242 in this example. Can anyone help me perform this conversion in Python 3? Thank you for your help.


Solution

  • Convert the data to an integer and shift five bits:

    data = b'\x1e@'
    print(int.from_bytes(data) >> 5)
    

    Output:

    242
    

    Ref: int.from_bytes()