[PYTHON-CRYPTO] string <-> int conversion
Bram Cohen
bram at GAWTH.COM
Fri Nov 9 20:21:26 CET 2001
On Fri, 9 Nov 2001, Paul Rubin wrote:
> The python library has no direct base 256 conversion function and it's
> too late to get a patch into 2.2. However, converting long to hex
> with hex(...) and then using binascii for binary output, or binascii
> for binary to hex followed by long(h,16) to convert hex to long, is
> reasonably fast.
Thanks, I feel stupid now. I cleaned up my routines to work that way, here
are the nicer versions -
from binascii import b2a_hex, a2b_hex
def int_to_binary(numin, size):
x = hex(numin)[2:]
if x[-1] == 'L':
x = x[:-1]
if len(x) % 2 == 1:
x = '0' + x
x = a2b_hex(x)
x = ('\000' * (size - len(x))) + x
return x
def binary_to_int(s):
return long(b2a_hex(s), 16)
I hate hate hate the int/long distinction and will do a dance on long()'s
grave when it's gone.
-Bram Cohen
"Markets can remain irrational longer than you can remain solvent"
-- John Maynard Keynes
More information about the python-crypto
mailing list