Tuesday, May 5, 2009

Python: formatting big integers

Write a one line Python function to format a big integer into fixed sized byte representation such that 0x0102030405 gets converted to '\x00\x00\x00\x01\x02\x03\x04\x05'. You cannot use struct module as it is limited to 32 bit number. Such functions are useful when dealing with SHA1/MD5 or crypto/RSA routines.

1 comment:

Kundan said...

Assuming Hsize represents the total number of bytes then int2bin does such conversion. The trick is to extract each byte from the integer.

int2bin = lambda x: (''.join(chr(a) for a in [((x>>c)&0x0ff) for c in xrange((Hsize-1)*8,-8,-8)])) if x is not None else '\x00'*Hsize