2

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?

0

3 Answers 3

5

int provides an alternative constructor for this:

>>> int.from_bytes(data[3] + data[4], 'big')
261
Sign up to request clarification or add additional context in comments.

Comments

3

You can use

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

or

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

Comments

2

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.