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

Question:

I running this code in python:

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

and I get the following output:

b'x01x00x02x00x00x00x00x00x03x00x00x00x00x00x00x00'

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?

Asked By: user20007266

||

Answers:

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.

Answered By: tdelaney
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.