pycom struct.pack is order dependent

Discussion and questions about boards that can run MicroPython but don't have a dedicated forum.
Target audience: Everyone interested in running MicroPython on other hardware.
Post Reply
KJM
Posts: 4
Joined: Sun Nov 18, 2018 10:53 pm

pycom struct.pack is order dependent

Post by KJM » Thu Jan 21, 2021 10:40 pm

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

User avatar
dhylands
Posts: 3601
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: pycom struct.pack is order dependent

Post by dhylands » Thu Jan 21, 2021 11:33 pm

it's due to alignment. A 4-byte integer needs to be aligned on a 4-byte boundary, so when you pack a byte followed by a 4-byte int, then 3 bytes of padding will be introduced.

Regular python3 behaves the same way.

Code: Select all

$ python3
Python 3.7.3 (default, Aug  4 2020, 19:30:55) 
[Clang 11.0.3 (clang-1103.0.32.62)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import struct
>>> bytes=struct.pack('sI', b'F', 1611017052); print(bytes, len(bytes))
b'F\x00\x00\x00\\+\x06`' 8
>>> bytes=struct.pack('Is', 1611017052, b'F'); print(bytes, len(bytes))
b'\\+\x06`F' 5
>>> 

KJM
Posts: 4
Joined: Sun Nov 18, 2018 10:53 pm

Re: pycom struct.pack is order dependent

Post by KJM » Sat Jan 23, 2021 1:03 am

Ahh, thnx for that, I'll stick the epoch at the front of the byte string & avoid the issue that way.

Post Reply