簡體   English   中英

Python struct.unpack 字節長度問題

[英]Python struct.unpack byte length issues

我有以下代碼:

msg = b'0,[\x00\x01\x86\xec\x96N'
print(struct.unpack("<"+"I",msg))

但是每次我嘗試這樣做時,它都會說

struct.error: unpack 需要 4 個字節的緩沖區

我試圖做的是以下

times = int(len(msg)/4)
 struct.unpack("<"+"I" * times,msg)

但它並不總是有效,我認為在奇數上,我怎樣才能得到正確的大小,所以我不會遇到這些問題?

struct.unpack要求消耗的緩沖區長度正好是格式的大小。 [1]

改用struct.unpack_from ,它要求消耗的緩沖區長度至少是格式的大小。 [2]

>>> msg = b'0,[\x00\x01\x86\xec\x96N'

>>> import struct
>>> print(struct.unpack("<"+"I", msg))
Traceback (most recent call last):
  File "<input>", line 1, in <module>
struct.error: unpack requires a buffer of 4 bytes

>>> print(struct.unpack_from("<"+"I", msg))
(5975088,)

unpack_from將忽略額外的字節

[1] https://docs.python.org/3/library/struct.html#struct.unpack
[2] https://docs.python.org/3/library/struct.html#struct.unpack_from

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM