Python struct.error: integer out of range for 'q' format code

Question:

I’m having a problem, I want to cast a binary number into a double precission number.

After some searchs, I found some way, but I’m still having a problem, I can cast “little” numbers but not the big ones (double precission), here’s my example code:

print unpack( "d", pack( "q", 4631069437225598976 ) )[ 0 ]
print unpack( "d", pack( "q", 13829563286724542464 ) )[ 0 ]

The first one has no problem, but the next one crashes with the error on the description.

The first number should be: 41.7274732
And the second one should be: -0.8899581

Any idea?

Thanks a lot

Asked By: josecgon

||

Answers:

Using Q for unsigned long long, instead of q for long long, will give the output you want:

from struct import pack, unpack

print unpack( "d", pack( "Q", 4631069437225598976 ) )[ 0 ]
print unpack( "d", pack( "Q", 13829563286724542464 ) )[ 0 ]

outputs:

41.7274742126
-0.889958143234

Edit:

please check carefully with your other big numbers because it might give the same error, we are just adding one bit in the most signicant bit position.

Answered By: progmatico

Consider reviewing the range for the format applicable to the data you’re using. I had a similar problem packing a positive 4 byte number as signed that was larger than 2147483647. Changing the format to unsigned allowed for inputs up to 4294967295 (packed as b’xffxffxffxff’).

From Python struct.pack() article on dqdongg.com and this comment on pyinstaller’s github I found the references needed to change the expected format for the data I was packing. The error message in this related question about format ranges would’ve been more helpful to understand the problem I was having, instead of "struct.error: argument out of range".

Format Type Quick Guide

Answered By: OwnDevise
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.