[英]Converting dynamic data to hex in array
我正在使用 python 中的智能卡并使用 pyscard 库。 我有以下数据:
WRITE_PREF = [0X80, 0X12, 0X00, 0X01, 0X12, 0X01, 0X00, 0X00, 0X20, 0X00, 0X00, 0X00]
我正在接收字符串格式的随机数据(长度为 10)。 转换为十六进制后,我得到包含随机字符串数据的十六进制值的数组。
问题:十六进制值数组具有字符串形式的值。
示例:['0x33','0x32'....]
当我 append WRITE_PREF 和这个十六进制数据时,我得到这样的数组:
[128, 18, 0, 1, 18, 1, 0, 0, 32, 0, 0, 0, '0x33', '0x32']
我将第一部分转换为十六进制,并将 integer 的数组值替换为十六进制。 当我使用命令传输数据时:
card.connection.transmit(final_array_in_hex)
我得到错误。 我很确定这是因为数组中的值是十六进制字符串。 如果我手动传输一些数据,例如:
[0x33,0x32,0x30]
它工作正常。 所以问题一定是因为数组数据中的引号。 例子:
['0x33','0x32','0x30']
有没有办法解决这个问题?
你有一个str
代表一个十六进制数,让我们把它变成一个int
。 我们使用int
节省空间, int
也很灵活。 我们可以选择如何表示这个int
。
s = ['0x33','0x32']
s = [int(_s, base=16) for _s in s]
print(s) # defaults to displaying an int as decimal
print(list(f'0x{_s:x}' for _s in s)) # specify that we want to display as `x` or hexamdecimal
Output:
[51, 50]
['0x33', '0x32']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.