Search code examples
pythonstructpack

struct pack return is too long


I'm trying to use the struct.pack function

import struct
values = (0, 44)
s = struct.Struct('HI')
b = s.pack(*values)
print(b)
print(str(len(b)))

and it gives me this output:

b'\x00\x00\x00\x00,\x00\x00\x00'
8

while the python docs say:

Format - C Type         - Python type - Standard size - Notes

H      - unsigned short - integer     - 2             - (3)

I      - unsigned int   - integer     - 4             - (3)

so len() should be 2 + 4 = 6, and I need bytes with size = 6

Any ideas?

I'm using Python 3.6 on Windows 10


Solution

  • pack will add pad bytes so that the second integer is 4 byte aligned. From the documentation:

    By default, the result of packing a given C struct includes pad bytes in order to maintain proper alignment for the C types involved; To ... omit implicit pad bytes, use standard size and alignment instead of native size and alignment: see Byte Order, Size, and Alignment for details