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

Lane, Frank L frank.l.lane at boeing.com
Mon Aug 22 19:31:23 CEST 2005



Hi Gang,

Thanks to Danny Yoo for a great answer.  The answer given is a little
advanced so I have to ask the following follow-up.

What does it mean when you write the [0] after the return statement?
e.g. return struct.unpack("!h", bytes)[0]

I'm really green here but can tell I'm going to love python! :-)

Thanks,
Frank

-----Original Message-----
From: Danny Yoo [mailto:dyoo at hkn.eecs.berkeley.edu] 
Sent: Friday, August 19, 2005 5:54 PM
To: Lane, Frank L
Cc: Tutor
Subject: Re: [Tutor] How do you turn something into a number?



> 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