String --> int

Samuele Pedroni pedroni at inf.ethz.ch
Thu Jun 21 08:58:39 EDT 2001


Romain Guy wrote:

>     Assuming fsock is a File objet, when I do:
> var = fsock.read(4)
> I get a String. I'd like to convert it into an integer. I haven't found any
> method for this so I built this one:
>
> def _buildInteger(bytes):
>   if len(bytes) != 4:
>     return -1
>   else:
>     return ord(bytes[0]) | ord(bytes[1]) << 8 | ord(bytes[2]) << 16 |
> ord(bytes[3]) << 24
>
> It works perfectly but I'd like to use one internal to Python if possible...
>
> --
> Romain "Java Swinguer !" Guy
> romain.guy at jext.org
> www.jext.org
>
> "Now, don't you worry. The saucers are up there. The graveyard is out there.
> But I'll be locked up safely in there."
> - Paula Trent, Plan 9 From Outer Space

struct.unpack should do what you are looking for.

http://www.python.org/doc/current/lib/module-struct.html

regards.




More information about the Python-list mailing list