question about binary and serial info

Grant Edwards grante at visi.com
Thu Aug 18 14:06:33 EDT 2005


On 2005-08-18, nephish at xit.net <nephish at xit.net> wrote:

>>>> import serial
>>>> ser = serial.Serial('/dev/ttyS0', 2400, timeout= 10, bytesize=8, stopbits=1)
>>>> a = ser.read(1)
>>>> print a
> ^

That's not a hex number.  Hex numbers are composed of '0-9A-F'

0F48A is a hex number. ^ is not a hex number.

>>>> ser.close()
>
>>>> type(a)
><type 'str'>
>
>>>> int(a, 16)
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
> ValueError: invalid literal for int(): ^

No big surprise there.  We've already seen that a is bound to
the string '^', and that isn't a hex number.

> so i run it again the same way, only reading 4 bytes this time.

It doesn't matter how many bytes you read.  If what you're
reading isn't a hex number, more of it still isn't a hex number.

>>>> ser = serial.Serial('/dev/ttyS0', 2400, timeout= 10, bytesize=8, stopbits=1)
>>>> a = ser.read(1)
>>>> print a
> ^AÜÀ
>>>> ser.close()
>
>>>> type(a)
><type 'str'>
>
>
> int(a, 16)
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
> ValueError: invalid literal for int(): ^AÜÀ

Again, not a hex number.  Hex numbers consist only of 0-9A-F.
Hex numbers do not contain ^ Ü or À.

> i dont understand what i am missing here. the string character
> represents a hex character.

No, it doesn't.  "Hex" is a base-16 string representation
consisting of the digits 0-9 and A-F[1].  The strings you're
reading are clearing not hex, since they consist of characters
other than 0-9 and A-F.  You appear to be reading binary data
of some sort.

If you want to convert a string of 4 8-bit bytes (which is what
you get when you do whatever.read(4)) integer, then you need to use the
struct module.  You're going to need to know whether the data
are being transmitted least significant byte first or most
significant byte first.

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

If all you want is to convert a single character (what you get
when you call whatever.read(1)), then all you need is the ord()
builtin:

 http://www.python.org/doc/current/ref/types.html#l2h-51


[1] Unless you're got base-16 hardware (which you don't), then
    the native hardware representation is hex.

-- 
Grant Edwards                   grante             Yow!  .. My pants just went
                                  at               on a wild rampage through a
                               visi.com            Long Island Bowling Alley!!



More information about the Python-list mailing list