Slava Slava - 1 year ago 111
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 Source

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 )


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download