Search code examples
pythonstructcastingdouble

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


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


Solution

  • 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.