struct pack 'q' format

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
robertjensen
Posts: 5
Joined: Tue Feb 24, 2015 12:21 am
Location: Maryland, USA

struct pack 'q' format

Post by robertjensen » Thu Mar 12, 2015 1:35 am

The struct.pack() function with the 'q' and 'Q' formats only seems to pack the lower 4 bytes of the argument. The struct.unpack() function operates on all 8 bytes of the input. Calling struct.calcsize('q') returns "8", as it should. A bug in the pack?

I tested this after upgrading to v1.3.10-165-gb761ed2, just to be sure it was not an out-of-date firmware issue.

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: struct pack 'q' format

Post by pythoncoder » Thu Mar 12, 2015 8:54 am

Are you using native or standard mode packing? From the Python documentation https://docs.python.org/3.4/library/struct.html:

The 'q' and 'Q' conversion codes are available in native mode only if the platform C compiler supports C long long, or, on Windows, __int64. They are always available in standard modes.
Peter Hinch
Index to my micropython libraries.

Damien
Site Admin
Posts: 647
Joined: Mon Dec 09, 2013 5:02 pm

Re: struct pack 'q' format

Post by Damien » Thu Mar 12, 2015 9:57 pm

'q' and 'Q' are not fully implemented on pyboard (due to it being a 32 bit arch). I've made an issue on github; https://github.com/micropython/micropython/issues/1155

Work around:

Code: Select all

struct.pack('<ii', long, long >> 32) # equivalent to '<q'

robertjensen
Posts: 5
Joined: Tue Feb 24, 2015 12:21 am
Location: Maryland, USA

Re: struct pack 'q' format

Post by robertjensen » Fri Mar 13, 2015 12:41 am

Damien, thanks. The fix you posted on github works fine both with positive and negative numbers. Could not Python do that same thing under the hood? The unpack works as is with the "q" format without any tricks.

Damien
Site Admin
Posts: 647
Joined: Mon Dec 09, 2013 5:02 pm

Post by Damien » Fri Mar 13, 2015 7:22 am

It could, but it's probably better to fix it properly :) Related is the need to support longs in int.to_bytes and int.from_bytes.

Post Reply