Byte to integer conversion

Christian Tismer tismer at appliedbiometrics.com
Thu Dec 16 15:23:27 EST 1999


Elefterios Stamatogiannakis wrote:
> 
>         How can i convert two, three, four bytes into an integer?

one byte is cheap with the ord function:

>>> ord("@")
64
>>> 

> 
>         I know a way with pickle, using loads() but i wonder is there
> a more elegant way of doing it.

There is the struct module which can do such stuff.

>>> import struct
>>> struct.unpack("b", "#")
(35,)
>>> struct.unpack("h", "xx")
(30840,)
>>> struct.unpack("i", "abcd")
(1684234849,)
>>> 

The three-byte case isn't handled there. If you are lazy
and just want it short, use

>>> arg="abc"
>>> struct.unpack("i", arg + "\0")
(6513249,)
>>> 

assuming little endian here of course.

>         I don't care about big, little endian problems

You should at least know it when you compute
your salary this way.

ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer at appliedbiometrics.com>
Applied Biometrics GmbH      :     Have a break! Take a ride on Python's
Kaiserin-Augusta-Allee 101   :    *Starship* http://starship.python.net
10553 Berlin                 :     PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint       E182 71C7 1A9D 66E9 9D15  D3CC D4D7 93E2 1FAE F6DF
     we're tired of banana software - shipped green, ripens at home




More information about the Python-list mailing list