简体   繁体   中英

Python struct.unpack byte length issues

I have the following code:

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

however everytime i try to do this it says

struct.error: unpack requires a buffer of 4 bytes

What i tried to do is the following

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

but it doesnt always work, i think on uneven numbers, how can i get the correct size so i dont encounter these issues?

struct.unpack requires that the length of the buffer being consumed is exactly the size of the format. [1]

Use struct.unpack_from instead, which requires that the length of the buffer being consumed is at least the size of the format. [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,)

Additional bytes will be ignored by 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM