2

I have a microcontroller connected to my computer via I2C connection, which sends back 1 byte of data at a time. I am trying to send a 4-byte number to the python program. I receive it in an array of individual bytes like this [123,45,67,89].

I need to convert that back into an integer in python. I am trying to use struct.unpack to do this, but I cannot get the data format correct. I am trying to get it in the form:

struct.unpack("I",b'x12\x34\x56\x78)

I don't know how to get the 4 bytes into the form required by struct. I can convert the numbers to hex, but don't know how to string them together.

2
  • It is quite unclear what you are asking. Can you edit your question and elaborate more? Commented Apr 23, 2016 at 13:24
  • I reformed it. Hopefully it is clearer. Commented Apr 23, 2016 at 13:45

1 Answer 1

5

You could convert it to a bytearray and pass that to struct.unpack().

import struct

data = [123, 45, 67, 89]

# Show hex values of data.
print(list('%02x' % b for b in data))  # -> ['7b', '2d', '43', '59']

# Convert to 4 byte unsigned integer data interpreting data as being in 
# little-endian byte order.
value = struct.unpack("<I", bytearray(data))[0]
print(hex(value))  # -> 0x59432d7b
Sign up to request clarification or add additional context in comments.

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.