将二进制文件从大英译为小英译。

问题描述 投票:0回答:1

我有一个大的二进制字节数组,我想把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个回答
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

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

© www.soinside.com 2019 - 2024. All rights reserved.