ValueError: invalid literal for int() with base 16: '\x0e\xa3' Python

69,066

I think you should use struct module and unpack your binary data like this:

struct.unpack("h", x)

Because int is not really for working with binary data, but with hexadecimal strings like: EF1D.

When you did x=ser.read(2) you received two bytes of binary data, there are two types of number representation supported by struct library: short(h) and unsigned short(H). Function struct.unpack receives two argument:

and returns a tuple with unpacked values(only one int in your case).

So you need to change string w=int(x, 16) to w = struct.unpack("h", x)[0] or to w = struct.unpack("H", x)[0], it depends on data type.

Share:
69,066
safsaf88
Author by

safsaf88

Updated on July 28, 2022

Comments

  • safsaf88
    safsaf88 almost 2 years

    I get bytes from the serial port which represents the voltage on my PIC board. But I can't convert these bytes(strings) to decimal because I get the error message above. Here is the function(in fact, it's associated with tkinter button)

    def channel8():
        ser.write(chr(0xFF))
        print "you have select channel8"
        x=ser.read(2)
        w=int(x, 16)
        print w
        print "Voltage on channel8 is:" , x
    

    ValueError: invalid literal for int() with base 16: '\x0e\xa3'

    def channel8():
        ser.write(chr(0xFF))
        print "you have select channel8"
        x=ser.read(2)
        z=struct.unpack("h", x)
        #w=int(z, 16)
        print z
    

    and i get this :

    Voltage on channel8 is: (28942,)

    can you please explain how did i get this value? it's not matching anything :D

  • Martijn Pieters
    Martijn Pieters almost 12 years
    The example int could be unsigned ('H'), value 41742, or signed, value -23794..
  • safsaf88
    safsaf88 almost 12 years
    thanks for the answer, can you explain more please? i'm a beginer :)
  • safsaf88
    safsaf88 almost 12 years
    great, i understand now, i put the result of your suggestion in my post (i've edited it) it gave me a decimal number but it is not matching result. For example, 0x0E6D gave me 27918 and it should be 3693
  • Fedor Gogolev
    Fedor Gogolev almost 12 years
    It means that your need to ">h" or ">H" struct specification. It means that uses big-endian byte order.
  • MarcusJ
    MarcusJ about 10 years
    what is "h" and x supposed to represent?