Slava Slava - 18 days ago 8
Python Question

How to pack big negative long to binary string in python

I need to calculate md5 hash of random 8 bytes long number, so I am trying to pack it:

import struct

num = 123L
bin = struct.pack( 'q', num )


which works fine, but for big negative values I get this error:

num = -14710095416404972671L
bin = struct.pack( 'q', num )



struct.error: long too large to convert to int


from python 2.6

Which way I can convert it to use as input for md5 hash?

Answer

You can't, that number just doesn't fit in an 8 byte long long (signed). The maximum value you can supply with 'q' is -2 ** 63, no less:

num = -2 ** 63 
bin = struct.pack('q', num )

while:

num = -2 ** 63 - 1
bin = struct.pack('q', num )

leads to error: argument out of range. That's the ceiling, with 'Q' you can achieve larger positive (unsigned) values but with a limit there of 2 ** 64.