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

前端 未结 1 1846
遇见更好的自我
遇见更好的自我 2020-12-16 04:44

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. He

相关标签:
1条回答
  • 2020-12-16 04:56

    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:

    • structure specification (a string of format characters)
    • binary data

    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.

    0 讨论(0)
提交回复
热议问题