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
That's a consequence of "Data structure padding". It will pad the
H
(2 bytes + 2 bytes padding) so that it aligns with theI
(4 bytes).However you can experiment with the order if you need to decrease the size. To quote Wikipedia:
For example on my computer it works if you just swap the
H
andI
:The size computation is not directly additive for the contained native types. You should compute the size using
struct.calcsize
:pack
will add pad bytes so that the second integer is 4 byte aligned. From the documentation: