Python 如何让数组中的 ASCII 编码十六进制被视为十六进制而不是字符串中的字符?

How to let ASCII coded hexadecimals in an array to be treated as hexadecimals and not as characters in a string by Python?

In [301]: string_to_write
Out[301]: '0x010x530x380x430x430x330x460x460x300x300x300x300x300x300x310x320x310x0D'

In [302]: len(string_to_write)
Out[302]: 72

In [303]: thestring="\x01\x53\x38\x43\x43\x33\x46\x46\x30\x30\x30\x30\x30\x30\x31\x32\x31\x0D"

In [304]: print thestring
S8CC3FF000000121

In [305]: len(thestring)
Out[305]: 18

我需要使用串行端口与设备通信,我需要向端口写入一个字符串。我通过键盘输入 thestring,同时我使用循环将每个十六进制字符写入 string_to_write。我需要将这个 string_to_write 转换成 thestring。如何使 Python 将四个字符组成的组识别为十六进制。

例如使用内置的编码库:

>>> "hello".encode("hex")
'68656c6c6f'
>>> "68656c6c6f".decode("hex")
'hello'
>>>

您需要将 string_to_write 分成长度为 4 的字符串,将这些字符串转换为整数,然后将这些整数中的每一个转换为字符。 Python 2 中有一种有效的方法(Python 3 中需要一种不同的方法)。请注意,此代码假定您的所有十六进制代码恰好包含 4 个字符,前导 0x。此脚本还使用 binascii.hexlify 以方便的格式打印输出数据。

from binascii import hexlify

def hex_to_bin(s):
    return ''.join([chr(int(''.join(u), 16)) for u in zip(*[iter(s)] * 4)])

s2w = '0x010x530x380x430x430x330x460x460x300x300x300x300x300x300x310x320x310x0D'
thestring = "\x01\x53\x38\x43\x43\x33\x46\x46\x30\x30\x30\x30\x30\x30\x31\x32\x31\x0D"

out = hex_to_bin(s2w)
print repr(thestring)
print repr(out)
print hexlify(out)
print thestring == out

输出

'\x01S8CC3FF000000121\r'
'\x01S8CC3FF000000121\r'
01533843433346463030303030303132310d
True   

也许你可以用这个作为例子:

string_to_write = '0x010x530x380x430x430x330x460x460x300x300x300x300x300x300x310x320x310x0D'
temp = [i for i in string_to_write.split('0x') if i]
print map(lambda x: int('0x'+x, 16), temp)

操作:

[1, 83, 56, 67, 67, 51, 70, 70, 48, 48, 48, 48, 48, 48, 49, 50, 49, 13]