Search code examples
pythonbinarybyteendianness

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?


Solution

  • 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