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

Alan Gauld ukc802591034 at btconnect.com
Sat Aug 20 10:23:09 CEST 2005


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

> data, address  = recvfrom (...stuff...)
> s = ""

This reads a sequence of bytes from the socket. What those bytes
represents only you can know. If they are a sequence of ascii codes
then they can be used as a string of characters. If they are binary
numbers then they could represent almost anthing and you will have
to figure out how to map or convert them to the appropriate
representation or format.

> number =int(s.join(data[10:13],16)) # turn two bytes of the string 
> into

But this is strange.
Starting at the inside it extracts bytes 10,11 and 12
it then passes them to s.join along with the value 16.
Thats not a valid call to join().

I therefore assume you intended to have the ')' before the 16
making the 16 a base value to int().

However, using base 16 implies that the three data elements extracted
have the ascii values of a hex string of numbers, is this the case?

If you actually only want the raw data you read the slice operation
is sufficient. If you want a hex string representation of those bytes
then you can use the hex() function.

> This yaks and says something about improper argument to int.

Thats almost certainly the bad parenthesis placement.

> I don't understand python's type system at all so any help
> here will be greatly appreciated.

You could look at the "raw materials" topic in my tutor for a
discussion of the various data types in Python. However they
are very conventional in form and behaviour.

HTH,


Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld 



More information about the Tutor mailing list