如何用Python按一定顺序打包

2024-05-16 07:53:37 发布

您现在位置: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)])

但是它很难看。有更简单的方法吗?你知道吗


Tags: 方法inforstructpackccccunpackx12
2条回答

编辑:正确方法:使用short并反转endian类型

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中没有现成的对混合endianness的支持。你知道吗

相关问题 更多 >