Python struct.pack and unpack

12,347

Solution 1

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

Solution 2

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?

Share:
12,347

Related videos on Youtube

Marcus F
Author by

Marcus F

Updated on June 04, 2022

Comments

  • Marcus F
    Marcus F almost 2 years

    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.

    • Collin Heist
      Collin Heist over 3 years
      If you want to reverse the packing, why don't you just not pack the elements in the first place?
    • Marcus F
      Marcus F over 3 years
      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 way
  • Marcus F
    Marcus F over 3 years
    how would one calculate the elements without knowing them=
  • Collin Heist
    Collin Heist over 3 years
    @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'.