Question

I have a Python array('B') (containing some data read from a file), which I would like to convert to an array('H'). I am currently using code similar to the following:

a = array.array('B', f.read())
b = a[16:32]
c = array.array('H', b.tostring())

Unfortunately the conversion in the third line uses the native byte order, so will give different results on different machines.

Is there any way to make the conversion always little-endian, irrespective of the native byte order?

Was it helpful?

Solution

array.array is only useful for internal calculations, because it always uses the native byte order. There is a method byteswap to change the order. Therefore you have to check sys.byteorder to determine the system byteorder, and swap accordingly.

To have better control of ordering use struct:

data = f.read()
c = struct.unpack_from('<8H', data, 16)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top