How to read integers from a file that are 24bit and little endian using Python?

Viewed 11435

Is there an easy way to read these integers in? I'd prefer a built in method, but I assume it is possible to do with some bit operations.
Cheers

edit
I thought of another way to do it that is different to the ways below and in my opinion is clearer. It pads with zeros at the other end, then shifts the result. No if required because shifting fills with whatever the msb is initially.

struct.unpack('<i','\0'+ bytes)[0] >> 8
5 Answers

Python 3 Method

In Python 3 I prefer using int.from_bytes() to convert a 3 byte representation into a 32 bit integer. No padding needed.

value = int.from_bytes(input_data[0:3],'big',signed=True)

or just

value = int.from_bytes(input_data)

If your array is only 3 bytes and representation is default.

Related