If I convert a character to bytes I get 1 byte
>>> bytes=struct.pack('s', 'F'); print(bytes, len(bytes)) b'F' 1
If I convert an epoch to bytes I get 4 bytes
>>> bytes=struct.pack('I', 1611017052); print(bytes, len(bytes)) b'\\+\x06`' 4
How come when I do both together I get 8 instead of 4+1=5 ??
bytes=struct.pack('sI', 'F', 1611017052); print(bytes, len(bytes)) b'F\x00\x00\x00\\+\x06`' 8
but this way I get the 5 I expect?
>>> bytes=struct.pack('Is', 1611017052, 'F'); print(bytes, len(bytes)) b'\\+\x06`F' 5
why is a different packing sequence giving different numbers of bytes?
This is related to the byte-alignment in struct, aligning to the longest used data type. As
Iis 4 bytes long, and
sis 1 byte, the total length of the structure will be either 5 or 8, depending on the alignment. As you put
sI, we would expect the character on the first index, and the integer on the second index, however, the controller knows these integers take 4 bytes, and expects the integer to start on the 5th index, as the 1st index already contains a character, therefor you get 3 null bytes after the character. This is expected behaviour
You can disable the alignment with an
>sign in the type definition