[英]Converting dynamic data to hex in array
I am working on a smartcard in python and using pyscard library.我正在使用 python 中的智能卡并使用 pyscard 库。 I have the following data:
我有以下数据:
WRITE_PREF = [0X80, 0X12, 0X00, 0X01, 0X12, 0X01, 0X00, 0X00, 0X20, 0X00, 0X00, 0X00]
WRITE_PREF = [0X80, 0X12, 0X00, 0X01, 0X12, 0X01, 0X00, 0X00, 0X20, 0X00, 0X00, 0X00]
I am receiving random data(of length 10) in string format.我正在接收字符串格式的随机数据(长度为 10)。 After conversion to hex, I get the array with hex values of the random string data.
转换为十六进制后,我得到包含随机字符串数据的十六进制值的数组。
Problem: The array of hex values has the values in string form.问题:十六进制值数组具有字符串形式的值。
Example: ['0x33','0x32'....]
示例:['0x33','0x32'....]
When I append WRITE_PREF and this hex data, I get the array like this:当我 append WRITE_PREF 和这个十六进制数据时,我得到这样的数组:
[128, 18, 0, 1, 18, 1, 0, 0, 32, 0, 0, 0, '0x33', '0x32']
[128, 18, 0, 1, 18, 1, 0, 0, 32, 0, 0, 0, '0x33', '0x32']
I convert the first part to hex and replace the array values of integer with the hex ones.我将第一部分转换为十六进制,并将 integer 的数组值替换为十六进制。 When I transmit data using the command:
当我使用命令传输数据时:
card.connection.transmit(final_array_in_hex)
I get error.我得到错误。 I am pretty sure it is because the values in array are hex strings.
我很确定这是因为数组中的值是十六进制字符串。 If I transmit some data manually like:
如果我手动传输一些数据,例如:
[0x33,0x32,0x30]
[0x33,0x32,0x30]
It is working fine.它工作正常。 So the problem must be because of the quotes in array data.
所以问题一定是因为数组数据中的引号。 Example:
例子:
['0x33','0x32','0x30']
['0x33','0x32','0x30']
Is there a way to solve this?有没有办法解决这个问题?
You have a str
representing a hexadecimal number, let's turn that into an int
.你有一个
str
代表一个十六进制数,让我们把它变成一个int
。 We save space using int
, also int
is flexible.我们使用
int
节省空间, int
也很灵活。 We can choose how to represent this 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: Output:
[51, 50]
['0x33', '0x32']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.