Python struct.pack and unpack
Asked Answered
S

2

9

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?

Stipulate answered 14/10, 2020 at 22:22 Comment(2)
If you want to reverse the packing, why don't you just not pack the elements in the first place?Impotence
ah yes, it's because i have data that needs to be interpreted by a receiver as bytes, however the receiver also responds with bytes packed in the same wayStipulate
I
15

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

Impotence answered 14/10, 2020 at 22:30 Comment(2)
how would one calculate the elements without knowing them=Stipulate
@EmilB, unless you know how the binary data is packaged, there is no way to infer the data types used to encode it. Think, if I were to give you any arbitrary bytes, you'd have no way of knowing what data that encodes. In your case, since you are both sender and receiver, this is a non-issue. But in general encoding to bytes (without some agreed upon structure) is hard to 'undo'.Impotence
C
1

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?

Clubhaul answered 14/10, 2020 at 22:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.