How can I convert a string sent over UART to integer in python?
Question: I'm having difficulty converting a string I'm receiving over UART to the
decimal version of it. I read in one byte with `port.read(1)` then print it

    
    
    print "%s: %s" % ( time.ctime(time.time()), str)
    

This prints out the expected character that matches with the decimal value for
that [ascii character](http://www.asciitable.com/index/asciifull.gif). I'm
sending known valued between 0 and 100. My issue is I can't convert this to
the decimal value and print that instead of say '*' for 42. I'm pretty sure
the default encoding/decoding is correct since the integer value in C is
showing the correct character when received in python.

It may also help to mention the sender is an AVR microcontroller programmed in
avr-gcc. I've messed around with decode('utf8'), decode("ISO-8859-1"), and
decode("ISO-8859-2") but again I'm pretty sure this is not what I want. I've
also tried converting the read value to a decimal with the int() function with
no luck. I get.

    
    
    ValueError: invalid literal for int() with base 10: '\xe4'
    


Answer: python works perfectly, it is your avr code that is broken.

remember what you are sending is a byte with the value 0 to 100, then on the
python side you are treating this byte as a string, but characters are mapped
through ascii or unicode character maps, so you are getting some characters,
but not necessary integer:

    
    
     In [1]> chr(48)
     Out[1]> '0'
    

So you can change the code on the avr, so instead of one byte it will send one
to three bytes, eg. '100' will consist of three bytes:

    
    
    '\x31\x30\x30' 
    # 49 48 48 - in decimal
    

or

you will convert data on the python side:

    
    
    value = port.read(1)  # reading one byte
    int_value = ord(value)
    
    # or using struct module - there you can decode multiple values in one go
    import struct
    
    int_value = struct.unpack('B', value)[0]  # struct always is returning tuple
    

