I’m using the struct module, and things aren’t going as I expected. Its due to some misunderstanding I have with the module I’m sure.
import struct
s = struct.Struct('Q');
print s.size
s = struct.Struct('H L Q');
print s.size
s = struct.Struct('H I Q');
print s.size
s = struct.Struct('H I Q H');
print s.size
The output of this is:
8
24
16
18
What am I missing here? Why are the second and third different sizes, and why is the fourth
not 16?
Alignment issue.
Assuming you’re running on a 64-bit non-Windows platform: Q and L will be 8-byte long, I is 4-byte, and H is 2-byte.
And these types must be put on a location which is a multiple of its size for best efficiency.
Therefore, the 2nd struct would be arranged as:
the 3rd struct:
and the 4th struct:
If you don’t want alignment, and require L to have 4 byte (the “standard” size), you’ll need to use the
=or>or<format, as described in http://docs.python.org/library/struct.html#struct-alignment:Demo: http://ideone.com/EMlgm