Nick Alexis
Nick Alexis

Reputation: 39

Python struct unpack multiple bytes with reverse endianess

So I have a buffer with N bytes and i read them with this, which works but has the reverse endianness from the one i need.

buffer=struct.unpack_from( 'h'*(N/2), databuff)

I noticed that endianness is reverse so I wanna experiment with endianess and I use this

buffer=struct.unpack_from( '<h'*(N/2), databuff)

However I get this error:

>>>buffer=struct.unpack_from( '<h'*1344, databuff) struct.error: bad char in struct format

How do I reverse endianness on multiple bytes?

Upvotes: 1

Views: 1147

Answers (1)

Davis Herring
Davis Herring

Reputation: 39878

You specify endianness at most once in a format, so write

buffer=struct.unpack_from('<'+'h'*(N//2), databuff)

where the // is Python 3 futureproofing.

Upvotes: 1

Related Questions