Convert little endian string to integer

Jeffrey Aylesworth picture Jeffrey Aylesworth · Nov 8, 2009 · Viewed 15.5k times · Source

I have read samples out of a wave file using the wave module, but it gives the samples as a string, it's out of wave so it's little endian (for example, \x00).

What is the easiest way to convert this into a python integer, or a numpy.int16 type? (It will eventually become a numpy.int16, so going directly there is fine).

Code needs to work on little endian and big endian processors.

Answer

Ned Batchelder picture Ned Batchelder · Nov 8, 2009

The struct module converts packed data to Python values, and vice-versa.

>>> import struct
>>> struct.unpack("<h", "\x00\x05")
(1280,)
>>> struct.unpack("<h", "\x00\x06")
(1536,)
>>> struct.unpack("<h", "\x01\x06")
(1537,)

"h" means a short int, or 16-bit int. "<" means use little-endian.