Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

python - Why does the output of struct.pack depend on the order of the items?

I'm trying to pack an epoch with a string & I can't figure out why the number of bytes depends on the order I do the packing in. Unfortunately I'm not getting any replies on the relevant microcontroller forum https://forum.pycom.io/topic/6761/struct

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'Fx00x00x00\+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?

question from:https://stackoverflow.com/questions/65836735/why-does-the-output-of-struct-pack-depend-on-the-order-of-the-items

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is a question of alignment. By default, struct packs according to standard C language conventions. This means that integers which are 4 bytes long are aligned on 4 byte boundaries. The start of the structure buffer is already aligned, so putting an integer first cause no padding. Putting a character first changes the offset to 1, so 3 bytes of padding are needed to get to a 4 byte boundary for a following integer.

This sort of padding is usually desirable, as some architectures may not allow the cpu to do an unaligned integer access, and others may do so much more slowly than an aligned access.

You can override the alignment by beginning the format with =:

bytes = struct.pack('=sI', b'F', 1611017052)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...