如何使用struct.unpack从python 3中的字节列表中提取int



假设我有一个具有恒定长度的列表位

>>> chunk = [b'xd0', b'x00', b'xd5', b'x00', b'xdf', b'x00', b'xaa', b'U']
>>> print(type(chunk))
<class 'list'>
>>> print(chunk)
[b'xd0', b'x00', b'xd5', b'x00', b'xdf', b'x00', b'xaa', b'U']

我想从中得到一个int,可以这样做:

>>> a = int.from_bytes(chunk[2], byteorder='little')
>>> b = int.from_bytes(chunk[3], byteorder='little')
>>> decoded = a * 256 + b
>>> print(decoded)
213

如何将struct.unpack用于此目的?我失败的几种方式:

>>> print(struct.unpack('<xxHxxxx', chunk))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'list'
>>> tmp = bytes(chunk)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'bytes' object cannot be interpreted as an integer
>>> tmp = bytes([chunk])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object cannot be interpreted as an integer
>>> tmp = bytearray(chunk)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'bytes' object cannot be interpreted as an integer

最初的动机是检查struct.unpack是否比已经工作的代码快。但现在我想找出正确的使用方法

哦,如果还有更有效的方法,我也很高兴知道!

问题在于如何将字节的list转换为bytes。您可以使用b''.join(list)执行此操作,然后应用结构解包。

示例:

>>> import struct
# your list of bytes
>>> lst = [b'xd0', b'x00', b'xd5', b'x00', b'xdf', b'x00', b'xaa', b'U']
# Convert into `bytes`
>>> bts = b''.join(lst)
# Unpack
>>> print(struct.unpack('<xxHxxxx', bts))
(213,)

请注意,您还可以使用对返回的元组进行解包

>>> (a,) = struct.unpack('<xxHxxxx', bts)
>>> a
213

最新更新