如何使用 Python 按特定顺序打包

How to pack in a certain order with Python

我想把0x12345678打包成\x34\x12\x78\x56

这是我写的

>>> a = struct.unpack('cccc', struct.pack('I', 0x12345678))
>>> struct.pack('cccc', [a[i] for i in (1,0,3,2)])

但是很丑。有更简单的方法吗?

编辑: 正确方法:使用 short 并反转字节序类型

import struct
a = struct.unpack('hh', struct.pack('I', 0x12345678))
struct.pack('>hh', *a)

较早的回答
您可以反转用法 ...

import struct
a1, a0, a3, a2 = struct.unpack('cccc', struct.pack('I', 0x12345678))
struct.pack('cccc', a0, a1, a2, a3)

但它产生了很多变数

或者,交换数组可以让您更轻松地传递结果:

import struct
a = struct.unpack('cccc', struct.pack('I', 0x12345678))
b = sum([[a[i+1], a[i]] for i in range(0, len(a), 2)], [])
struct.pack('cccc', *b)

注意:它们可能是更好的交换方式:)

一种方法是将它拆分成短裤然后重新组合,尽管它几乎同样丑陋:

def pack(x):
    return struct.pack('<hh', x >> 16, x & 0xffff)

>>> pack(0x12345678).encode('hex')
'34127856'

据我所知,Python 中没有现成的混合字节序支持。