Best way to convert sequence of bytes to long integer

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Jan 20 16:23:24 EST 2010


On Wed, 20 Jan 2010 19:27:34 +0100, Alf P. Steinbach wrote:

> * Mark Dickinson:
>> On Jan 20, 7:36 am, Steven D'Aprano <st... at REMOVE-THIS-
>> cybersource.com.au> wrote:
>>> I have a byte string (Python 2.x string), e.g.:
>>>
>>> s = "g%$f yg\n1\05"
>>> assert len(s) == 10
>>>
>>> I wish to convert it to a long integer, treating it as base-256.
>> 
>> By the way, are you willing to divulge what you're using this
>> functionality for?  When trying to hack out the API for int.to_bytes
>> and int.from_bytes on the mailing list and bug tracker, some of the
>> discussion about use-cases seemed a little too much like guesswork; I'd
>> be curious to find out about real-life use-cases.
> 
> One possibility is that Steven wants to apply bitlevel and/or arithmetic
> operations for e.g. some custom cryptographic thing. The string that he
> uses as example is not completely unlike a message digest.

Good guess!

I'm writing a module that handles, I won't call it encryption, 
obfuscation using classical cryptographic algorithms. One of the 
functions needs a deterministic but unpredictable integer generated from 
a human-generated password or passphrase, so I'm using:

hashlib.md5(key).digest()

to get a string of bytes, then converting it to an int.

int.from_bytes would be perfect for me, but in the meantime I'm using 
Paul Rubin's trick of int(s.encode("hex"), 16).

Thanks to all who responded.


-- 
Steven



More information about the Python-list mailing list