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将每个由四个字符组成的组标识为十六进制。你知道吗
也许你可以用这个作为例子:
操作:
只需使用内置的encode lib,例如:
您需要将
string_to_write
切分为长度为4的字符串,将这些字符串转换为整数,然后将每个整数转换为字符。在Python2中有一种有效的方法可以做到这一点(在Python3中需要一种不同的方法)。请注意,此代码假定所有十六进制代码都正好包含4个字符,前导为0x
。此脚本还使用binascii.hexlify
以方便的格式打印输出数据。你知道吗输出
相关问题 更多 >
编程相关推荐