Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 2 byte from byte array to one integer

I have a list of bytearrays that looks like that :

data = [
   bytearray(b'\x01'),
   bytearray(b'\x03'),
   bytearray(b'\x04'),
   bytearray(b'\x01'),
   bytearray(b'\x05'),
   bytearray(b'\x00'),
   bytearray(b'\xC0'),
   bytearray(b'\xfa'),
   bytearray(b'3')
]

This array is what I read from a sensor. What I need is to uses data[3] and data[4] together (so 01 05 ) to convert this into an integer (should be 261) to get a value from the sensor. I struggle to do it. Can anyone help please?

like image 767
zacknafein Avatar asked Jun 27 '26 12:06

zacknafein


1 Answers

int provides an alternative constructor for this:

>>> int.from_bytes(data[3] + data[4], 'big')
261
like image 189
juanpa.arrivillaga Avatar answered Jun 30 '26 01:06

juanpa.arrivillaga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!