Reading a multi-byte number

Tim Peters tim.one at comcast.net
Mon May 19 17:28:35 EDT 2003


[Batista, Facundo]
> I've written this one:
>
> >>> def strToInt(value):
> ...     cad = ""
> ...     for carac in value:
> ...             cad += hex(ord(carac))[2:]
> ...     return eval("0x" + cad)

In Python 2.3, this is likely the fastest:

    from binascii import hexlify

    def bytes2int(bytestring):
        return int(hexlify(bytestring), 16)

Before Python 2.3, use long() instead of int() in the body to avoid
OverflowError.

In 2.3, the function takes time linear in len(bytestring).  Before 2.3, and
like yours, it takes time quadratic in len(bytestring).  This is because
long(bigstring, 16) itself takes time quadratic in len(bigstring) before
2.3.  Multiplying by 256 inside the loop would also be overall
quadratic-time, of course (if you like that for some other reason, at least
shift left 8 instead; *still* quadratic-time then, but faster).






More information about the Python-list mailing list