zacknafein
zacknafein

Reputation: 50

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?

Upvotes: 2

Views: 1526

Answers (3)

hhz
hhz

Reputation: 116

A readable solution would be:

temp = data[3] + data[4]
r = int.from_bytes(temp, byteorder='big', signed=False)

Combining the bytearrays and using the from_bytes method to create an integer (which is indeed 261 with byteorder 'big' and unsigned).

Upvotes: 2

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96350

int provides an alternative constructor for this:

>>> int.from_bytes(data[3] + data[4], 'big')
261

Upvotes: 5

Selcuk
Selcuk

Reputation: 59444

You can use

data[3][0] * 256 + data[4][0]

or

data[3][0] << 8 | data[4][0]

Upvotes: 3

Related Questions