问题描述
我使用 pyqt5 行编辑框作为我的输入框。我想从输入框中获取输入并将其从字符串转换为十六进制以发送到串行捕获。例如,我这样做了,但没有成功:
a = hex(self.slave1.text())
b = hex(self.function1.text())
c = hex(self.address_msb1.text())
d = hex(self.address_lsb1.text())
e = hex(self.register_msb1.text())
f = hex(self.register_lsb1.text())
g = hex(self.crc_lsb1.text())
h = hex(self.crc_msb1.text())
hexConvert = [a,b,c,d,e,f,g,h]
想象一下:
a = "01"
b = "03"
c = "00"
d = "0A"
e = "00"
f = "04"
g = "64"
h = "0B"
我的预期输出是
[0x01,0x03,0x00,0x0A,0x04,0x64,0x0B]
解决方法
hex() 函数将指定的整数转换为十六进制字符串表示。
使用 int(x,base)
以 16 为基数将字符串 x 转换为整数。将整数作为数字调用 hex(number) 将其转换为十六进制。
hex_string = "0xAA"
"0x" also required
an_integer = int(hex_string,16)
hex_value = hex(an_integer)
print(hex_value)
输出
0xaa