Best way to convert sequence of bytes to long integer
Peter Otten
__peter__ at web.de
Wed Jan 20 03:43:30 EST 2010
Steven D'Aprano 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.
> Currently I'm using:
>
> def makelong(s):
> n = 0
> for c in s:
> n *= 256
> n += ord(c)
> return n
>
>
> which gives:
>
>>>> makelong(s)
> 487088900085839492165893L
>
>
> Is this the best way, or have I missed some standard library function?
The pickle module uses
>>> import binascii
>>> s = "g%$f yg\n1\05"
>>> long(binascii.hexlify(s), 16)
487088900085839492165893L
Peter
More information about the Python-list
mailing list