python hex() 的问题
Issues with python hex()
我有 json 文件如下
{
"devices" :[
{
"Manufacturer name": "Sony",
"vendor_id":"8087" ,
"product_id" : "07da"
},
{
"Manufacturer name": "Sandisk",
"vendor_id": "1d6b",
"product_id" : "0002"
},
{
"Manufacturer name": "Chicony Electronics",
"vendor_id": "04f2",
"product_id" : "b381"
}
]
}
此 json 文件包含连接到我笔记本电脑的 USB 设备的供应商和产品 ID。我正在使用此 json 文件检查 USB 设备是否已连接到笔记本电脑。供应商和产品 ID 在 hex
中。由于 json
不能使用 hex
,我将这些值写成字符串格式。我实际上正在使用 python 的 pyusb
模块来检查设备的连接性,如下所示
import usb.core
def get_hex(hex_str):
hex_int = int(hex_str, 16)
return hex(hex_int)
vendor_id = get_hex("8087")
product_id = get_hex("07da")
dev = usb.core.find(idVendor=vendor_id, idProduct=product_id)
if dev is None:
print "Disconnected"
else:
print "Connected"
但是当我 运行 这段代码时,我得到的打印消息是 "Disconnected"
这里实际上的问题是 usb.core.find()
函数需要 int
中的值,但是值 get_hex()
函数 returns 是 string
。一旦将上面代码中的 dev = usb.core.find(idVendor=vendor_id, idProduct=product_id)
行更改为 dev = usb.core.find(idVendor=0x8087, idProduct=0x07da)
。上面的代码工作正常。请让我知道如何 return 在 int
中 get_hex()
的值。
问题是您将十六进制字符串转换为 int,然后再转换回十六进制字符串。将其转换为 int 后只需 return。最好将该函数重命名为 get_int
,因为您只是将其转换为 int
def get_int(hex_str):
return int(hex_str, 16)
vendor_id = get_int("8087")
product_id = get_int("07da")
dev = usb.core.find(idVendor=vendor_id, idProduct=product_id)
我有 json 文件如下
{
"devices" :[
{
"Manufacturer name": "Sony",
"vendor_id":"8087" ,
"product_id" : "07da"
},
{
"Manufacturer name": "Sandisk",
"vendor_id": "1d6b",
"product_id" : "0002"
},
{
"Manufacturer name": "Chicony Electronics",
"vendor_id": "04f2",
"product_id" : "b381"
}
]
}
此 json 文件包含连接到我笔记本电脑的 USB 设备的供应商和产品 ID。我正在使用此 json 文件检查 USB 设备是否已连接到笔记本电脑。供应商和产品 ID 在 hex
中。由于 json
不能使用 hex
,我将这些值写成字符串格式。我实际上正在使用 python 的 pyusb
模块来检查设备的连接性,如下所示
import usb.core
def get_hex(hex_str):
hex_int = int(hex_str, 16)
return hex(hex_int)
vendor_id = get_hex("8087")
product_id = get_hex("07da")
dev = usb.core.find(idVendor=vendor_id, idProduct=product_id)
if dev is None:
print "Disconnected"
else:
print "Connected"
但是当我 运行 这段代码时,我得到的打印消息是 "Disconnected"
这里实际上的问题是 usb.core.find()
函数需要 int
中的值,但是值 get_hex()
函数 returns 是 string
。一旦将上面代码中的 dev = usb.core.find(idVendor=vendor_id, idProduct=product_id)
行更改为 dev = usb.core.find(idVendor=0x8087, idProduct=0x07da)
。上面的代码工作正常。请让我知道如何 return 在 int
中 get_hex()
的值。
问题是您将十六进制字符串转换为 int,然后再转换回十六进制字符串。将其转换为 int 后只需 return。最好将该函数重命名为 get_int
,因为您只是将其转换为 int
def get_int(hex_str):
return int(hex_str, 16)
vendor_id = get_int("8087")
product_id = get_int("07da")
dev = usb.core.find(idVendor=vendor_id, idProduct=product_id)