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

2024-09-21 02:58:30 发布

您现在位置: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

我需要使用串行端口与设备通信,我需要向端口写入一个字符串。我通过键盘输入字符串,同时我使用loop将每个十六进制字符写入字符串。我需要将这个字符串\u to \u write转换成字符串。如何让Python将每个由四个字符组成的组标识为十六进制。你知道吗


Tags: to端口字符串instringlenout字符
3条回答

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

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]

只需使用内置的encode lib,例如:

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

您需要将string_to_write切分为长度为4的字符串,将这些字符串转换为整数,然后将每个整数转换为字符。在Python2中有一种有效的方法可以做到这一点(在Python3中需要一种不同的方法)。请注意,此代码假定所有十六进制代码都正好包含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   

相关问题 更多 >

    热门问题