Reading a multi-byte number

Steven Taschuk staschuk at telusplanet.net
Mon May 19 16:30:28 EDT 2003


Quoth Batista, Facundo:
  [...]
> When I must read a (8 * n)bit number, I need a for (this code it's not
> tested):
> 
> def strInt(cadena):
>         exponentes =  range(len(cadena)-1, -1, -1)
>         valor = 0
>         for ind in range(len(cadena)):
>                 car = cadena[ind]
>                 exp = exponentes[ind]
>                 valor += ord(car) * (255 ^ exp)

(Btw, shouldn't that be "255**exp"?)

>         return valor
> 
> There's a builtin way to do this?

Not that I know of, but perhaps you'd prefer

    def bytes2int(string):
        i = 0
        for ch in string:
            i = 255*i + ord(ch)
        return i

which seems simple and straightforward to me.  If you're a fan of
map and kin, there's also

    def bytes2int(string):
        return reduce(lambda x, y: 255*x + y, map(ord, string), 0L)

-- 
Steven Taschuk                                                 o- @
staschuk at telusplanet.net                                      7O   )
                                                               "  (





More information about the Python-list mailing list