Reputation: 44268
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:
num = -14710095416404972671L
bin = struct.pack( 'q', num )
I get this error:
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?
Upvotes: 3
Views: 407
Reputation: 40839
You have a variety of choices, as soon as you realise MD5 operates on any byte stream. It is important to note that sign does not matter for MD5; it does not interpret integers, it manipulates a stream. Therefore you don't need to care about the sign of your input or converting to signed integers. You need a byte array, which you can obtain in multiple ways, my preference is:
In [30]: 0xEB95EC9D994ED78D.to_bytes(8, 'big')
Out[30]: b'\xeb\x95\xec\x9d\x99N\xd7\x8d'
which will handle arbitrary integers within the limits Python's integers allow.
Upvotes: 1
Reputation: 160557
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
.
Upvotes: 1