pythonpython-3.xintegerhexbyte

How do I convert a byte to an integer in python when it has the byte markers attached?


I have a function in python which reads the first 3 bytes in a serial port buffer. I then want to convert the third byte to an integer which will allow me to determine the length of the total byte array. However, when I use int() I get the following error:

ValueError: invalid literal for int() with base 16: b'\x16'

I've tried slicing the string further along, but that just returns b''. How can I convert the byte to an integer?

Thank you!


Solution

  • Use int.from_bytes().

    >>> int.from_bytes(b'\x00\x10', byteorder='big')

    16

    >>> int.from_bytes(b'\x00\x10', byteorder='little')

    4096

    >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)

    -1024

    >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)

    64512

    >>> int.from_bytes([255, 0, 0], byteorder='big')

    16711680