【问题标题】:Convert binary file from big to little endiand将二进制文件从大端转换为小端
【发布时间】:2020-05-12 13:34:36
【问题描述】:

我有一个大的二进制字节数组,我想将其从 32 位的大端更改为小端

例如 b 0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88 到 b 0x44,0x33,0x22,0x11,0x88,0x77,0x66,0x55

如何在 python 中做到这一点?

【问题讨论】:

标签: python python-3.x python-2.7 endianness


【解决方案1】:

有很多方法可以做到这一点,这里是其中之一:

data = bytearray(b'\x01\x02\x03\x04\x05\x06\x07\x08')
ref = bytearray(b'\x04\x03\x02\x01\x08\x07\x06\x05')

for offset in range(0, len(data), 4):
    chunk = data[offset:offset + 4]
    if len(chunk) != 4:
        raise ValueError('alignment error')
    data[offset:offset + 4] = chunk[::-1]

assert data == ref

这样你可以在不复制数组的情况下改变字节顺序。

【讨论】:

    猜你喜欢
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 2013-10-17
    相关资源
    最近更新 更多