Combine byte values to a 32bib int

I get 4 8bit (1 Byte) values from a i.e. serial input. In fact it is unix time in pieces, but to work with it I need it in one 32 bit int.

Tried something with shift >> and << but got not what I want
Any help or hint Thank you

Rainer

One way to do it is to simply concatenate the bytes and then convert.

Let’s say that you got something like now_bytes from a serial connection:

import time

now = int(time.time())
print(now)  # E.g. 1737373766
now_bytes = list(now.to_bytes(length=4, byteorder="big"))
print(now_bytes)  # E.g. [103, 142, 56, 70]

Then you can do this:

timestamp = int.from_bytes(bytes(now_bytes), byteorder="big")
print(timestamp)  # E.g. 1737373766

The above assumes the serialized timestamp was received MSB first, aka. big endian.

2 Likes

Whether it’s a signed ('i' / int32 ) or unsigned('I' / uint32) integer was not specified, but try:

struct.unpack('i', ...)

If the data is a Unix timestamp, signedness doesn’t matter if it corresponds to a date in the range 1970-01-01 - 2038-01-18.

You need to be careful with endianness, though. You should be explicit about endianness, especially when working with data received over a network.

To specify e.g. big endian data in the struct module, use ">" in the format string: struct.unpack(">i", ...).

1 Like

Perfect thank you

# code receiving data1, data2, data3, data4
now_bytes = [data1,data2,data3,data4]
print(now_bytes)
timestamp = int.from_bytes(bytes(now_bytes), byteorder="big")
print(timestamp)