2

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!

clubby789
  • 2,543
  • 4
  • 16
  • 32
Nadim
  • 77
  • 1
  • 2
  • 9

3 Answers3

5

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

Community
  • 1
  • 1
clubby789
  • 2,543
  • 4
  • 16
  • 32
0

You can use the stuct module. But it work with 4 bytes (int)

import struct

(length,) = struct.unpack('!I', my_binary)
Yassine Faris
  • 951
  • 6
  • 26
0

Assuming you are using Python 3, you can just index the byte array and use the value directly as an integer. e.g.

>>> v = b"\0\1\2"
>>> v[2]
2
>>> v[2] + 1
3
Deepstop
  • 3,627
  • 2
  • 8
  • 21