문제

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?

도움이 되었습니까?

해결책

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)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top