Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python struct.pack and unpack

I want to reverse the packing of the following code:

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

I know "<" means little endian and "I" is unsigned int. How can I use struct.unpack to reverse the packing?

like image 787
Marcus F Avatar asked Apr 22 '26 09:04

Marcus F


2 Answers

struct.pack takes non-byte values (e.g. 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) - e.g. struct.unpack('<' + 'I' * elements, value).

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

like image 161
Collin Heist Avatar answered Apr 23 '26 22:04

Collin Heist


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?

like image 29
Rolv Apneseth Avatar answered Apr 23 '26 23:04

Rolv Apneseth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!