Page 1 of 1

struct pack 'q' format

Posted: Thu Mar 12, 2015 1:35 am
by robertjensen
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.

Re: struct pack 'q' format

Posted: Thu Mar 12, 2015 8:54 am
by pythoncoder
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.

Re: struct pack 'q' format

Posted: Thu Mar 12, 2015 9:57 pm
by Damien
'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'

Re: struct pack 'q' format

Posted: Fri Mar 13, 2015 12:41 am
by robertjensen
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.

Posted: Fri Mar 13, 2015 7:22 am
by Damien
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.