struct
-
If I convert a character to bytes I get 1 byte
>>> bytes=struct.pack('s', 'F'); print(bytes, len(bytes)) b'F' 1If I convert an epoch to bytes I get 4 bytes
>>> bytes=struct.pack('I', 1611017052); print(bytes, len(bytes)) b'\\+\x06`' 4How 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`' 8but this way I get the 5 I expect?
>>> bytes=struct.pack('Is', 1611017052, 'F'); print(bytes, len(bytes)) b'\\+\x06`F' 5why 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, andsis 1 byte, the total length of the structure will be either 5 or 8, depending on the alignment. As you putsI, 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 behaviourYou can disable the alignment with an
<or>sign in the type definition -
@Gijs tnx
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login