[Tutor] How do you turn something into a number?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sat Aug 20 00:53:50 CEST 2005



> I have what I think is a string from socket.recvfrom(...).  I want to
> turn it into numbers

Hi Frank,

If you know how those bytes should be interpreted, you may want to look at
the 'struct' module to destructure them back into integers:

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



> from socket import *
> from array import *

Side note: you may want to avoid doing the 'from <foo> import *' form in
Python, just because there's a high chance that one module will munge the
names of another.  If you want to avoid typing, you can always abbreviate
module names by doing something like this:

######
import socket as S
import array as A
######

For more information on this, see:

    http://www.python.org/doc/tut/node8.html#SECTION008410000000000000000




Ok, let's continue looking at some code:

[some code cut]

> number =int(s.join(data[10:13],16))


I think you meant to write:

    number = int(data[10:13], 16)

But even with the correction, this will probably not work: int() expects
to see string literals, not arbitrary byte patterns that come off the
socket.recv_from.


I think you want to use 'struct' instead.  For example:

######
>>> import struct
>>> struct.calcsize("h")
2
######

On my platform, a "short" is two bytes.


######
>>> def parse_short(bytes):
...     """Given two bytes, interprets those bytes as a short."""
...     return struct.unpack("h", bytes)[0]
...
>>> parse_short('\x01\x00')
1
>>> parse_short('\x00\x01')
256
######


And from this example, we can see that I'm on a "little-endian" system.

    http://catb.org/~esr/jargon/html/L/little-endian.html


So we probably do need to take care to tell 'struct' to interpret the
bytes in "network" order, bu using the '!' prefix during the byte
unpacking:

######
>>> def parse_short(bytes):
...     """Given two bytes, interprets those bytes as a short."""
...     return struct.unpack("!h", bytes)[0]
...
>>> parse_short('\x01\x00')
256
>>> parse_short('\x00\x01')
1
######


Please feel free to ask questions on this.  Hope this helps!



More information about the Tutor mailing list