简体   繁体   中英

Python struct.pack and unpack

Im in no way an experienced python programmer,thats why i believe there may be an obvious answer to this but i just can't wrap my head around the struct.pack and unpack. i have the following code:

struct.pack("<"+"I"*elements, *self.buf[:elements])

I want to reverse the the packing of this, however im not sure how, i know that "<" means little endian and "I" is unsigned int and thats about it, im not sure how to use struct.unpack to reverse the packing.

struct.pack takes non-byte values (eg integers, strings, etc.) and converts them to bytes . And conversely, struct.unpack takes bytes and converts them to their 'higher-order' equivalents.

For example:

>>> from struct import pack, unpack
>>> packed = pack('hhl', 1, 2, 3)
>>> packed
b'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpacked = unpack('hhl', packed)
>>> unpacked
(1, 2, 3)

So in your instance, you have little-endian unsigned integers ( elements many of them). You can unpack them using the same structure string (the '<' + 'I' * elements part) - eg struct.unpack('<' + 'I' * elements, value) .

Example from: https://docs.python.org/3/library/struct.html

Looking at the documentation: https://docs.python.org/3/library/struct.html

obj = struct.pack("<"+"I"*elements, *self.buf[:elements])
struct.unpack("<"+"I"*elements, obj)

Does this work for you?

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