I have just tried using struct.pack in Python for the first time, and I don't understand its behaviour when I am mixing types
When I am trying to pack a single char and nothing else, it works as expected, i.e.
struct.pack("b",1)
gives '\x01'
. But as soon as I try to mix in data of a different type, the char is padded to be as long as this type, e.g.
struct.pack("bi",1,1)
gives '\x01\x00\x00\x00\x01\x00\x00\x00'
.
Is this standard behaviour, and why? Is there a way around it?
Edit
More simply put:
>>> struct.calcsize("b")
1
>>> struct.calcsize("i")
4
>>> struct.calcsize("bi")
8
struct.calcsize('d')
→ 8,struct.calcsize('bd')
→ 16. Alignment and padding seems to be depending on the other types. That's not intuitive, even if you expect alignment. EDIT: Ah, I see, the size of the'd'
is 8, and that determines where it can start (at multiples of 8), hence the padding. – Dorastruct.calcsize('db')
is 9 (note that in C, it would usually be 12 as words need to be filled completely). – Petulah