简体   繁体   English

将Python数组('B')转换为数组('H') - 总是小端?

[英]Convert Python array('B') to array('H') - always little-endian?

I have a Python array('B') (containing some data read from a file), which I would like to convert to an array('H') . 我有一个Python array('B') (包含从文件中读取的一些数据),我想将其转换为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? 有没有办法使转换始终是little-endian,无论本机字节顺序如何?

array.array is only useful for internal calculations, because it always uses the native byte order. array.array仅对内部计算有用,因为它始终使用本机字节顺序。 There is a method byteswap to change the order. 有一个方法byteswap来改变顺序。 Therefore you have to check sys.byteorder to determine the system byteorder, and swap accordingly. 因此,您必须检查sys.byteorder以确定系统字节顺序,并相应地进行交换。

To have better control of ordering use struct : 为了更好地控制排序使用struct

data = f.read()
c = struct.unpack_from('<8H', data, 16)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM