Conversion from string to integer

Peter Otten __peter__ at web.de
Wed Mar 22 14:02:30 EST 2006


xkenneth wrote:

> I've been attempting to write a serial program in python. I talk to
> a custom designed bit of hardware that sends me back groups that are 2
> bytes in length. When i recieve them using either pySerial or USPP i'm
> not sure how python interprets them. Both of the bytes should be
> interpreted as one integer. I store each of the two bytes in a python
> array. Here is an example of the data as printed in a terminal.
> 
> ['\x1dz', '\xa8<', '\x89{', '}O', 'r\xaf', '\x83\xcd', '\x81\xba',
> '\x00\x02', '\x00\x00', '\x00\x00', '\x00\x00']
> 
> As you can see it either chooses to represent one byte in hex or one in
> ascii or both in hex etc. I'm just not sure how to get this into an
> integer format.

Your data consists entirely of two-byte strings; don't get fooled by the way
Python represents them. To convert them you need struct.unpack() which
seems to be in high demand today:

>>> data = ['\x1dz', '\xa8<', '\x89{', '}O', 'r\xaf', '\x83\xcd',
'\x81\xba',
... '\x00\x02', '\x00\x00', '\x00\x00', '\x00\x00']
>>> print [struct.unpack("h", s)[0] for s in data]
[7546, -22468, -30341, 32079, 29359, -31795, -32326, 2, 0, 0, 0]

Of course "h" is only one of the candidates for the format parameter. See
http://docs.python.org/lib/module-struct.html for the complete list.

Peter




More information about the Python-list mailing list