Search code examples
pythonpython-3.xbytepack

Why I get this output while I trying to print this packed struct?


I running this code in python:

import struct
res = struct.pack('hhl', 1, 2, 3)
print(res)

and I get the following output:

b'\x01\x00\x02\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00'

but I don't understand why this is the output? after all, the format h means 2 bytes, and the format l means 4 bytes. so why i get this output in this case?


Solution

  • From the struct doc,

    To handle platform-independent data formats or omit implicit pad bytes, use standard size and alignment instead of native size and alignment

    By default h may be padded, depending on the platform you are running on. Select "big-endian" (>), "little-endian" (<) or the alternate native style (=) to remove padding. For example,

    >>> struct.Struct('hhl').size
    16
    >>> struct.Struct('<hhl').size
    8
    >>> struct.Struct('>hhl').size
    8
    >>> struct.Struct('=hhl').size
    8
    

    You would choose one depending on what pattern you are trying to match. If its a C structure for a natively compiled app, it depends on native memory layout (e.g., 16 bit architectures) and whether the compiler packs or pads. If a network protocol, big or little endian, depending on its specification.