ValueError:使用基数16的int()的无效文本:'\x0e\xa3'Python [英] ValueError: invalid literal for int() with base 16: '\x0e\xa3' Python
问题描述
我从串行端口获得了一些字节,这些字节代表了PIC板上的电压。
但是我无法将这些字节(字符串)转换为十进制,因为我收到上面的错误消息。
这是函数(实际上,它与tkinter按钮相关联)
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 :以int()为基数16的无效文字:'\x0e\xa3'
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
我得到这个:
channel8的电压为:(28942,)
Voltage on channel8 is: (28942,)
您能解释一下我是怎么得到这个值的吗?它不匹配任何东西:D
can you please explain how did i get this value? it's not matching anything :D
推荐答案
我认为您应该使用 struct 模块并解压缩二进制数据,如下所示:
I think you should use struct module and unpack your binary data like this:
struct.unpack("h", x)
因为 int
不是真正用于处理二进制数据,而是使用十六进制字符串,例如: EF1D
。
Because int
is not really for working with binary data, but with hexadecimal strings like: EF1D
.
当您执行 x = ser.read(2)
时,您收到了两个字节的二进制数据,其中有两个 struct
库支持的数字表示类型: short
(h)和 unsigned short
(H)。函数 struct.unpack
接收两个参数:
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:
- 结构规范(字符串< a href = http://docs.python.org/library/struct#format-characters rel = nofollow noreferrer>格式化字符)
- 二进制数据
并返回带有未打包值的元组(在您的情况下只有一个int)。
and returns a tuple with unpacked values(only one int in your case).
因此,您需要将字符串 w = int(x,16)
更改为 w = struct.unpack( h,x)[ 0]
或 w = struct.unpack( H,x)[0]
,取决于数据类型。
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.
这篇关于ValueError:使用基数16的int()的无效文本:'\x0e\xa3'Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!