将PySerial Readline从字符串转换为二进制

2024-10-01 18:34:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我从PIC微控制器发送bytestring 0x0F,0x07,0x55,0x55,0x55。在

通过Python的串行端口,我使用PySerial中的readlines()命令。我收到:

['\x0f\x07UUU']

这确实与我发送的bytestring相对应,但是它的格式看起来像是十六进制和ASCII字符的奇怪组合。有什么好方法可以将它格式化回0x0F、0x07、0x55、0x55、0x55?在


Tags: 方法端口命令格式ascii字符pyserialpic
3条回答

在python2中,bytestring(str)是一个由8位字符组成的字符串,因此它看起来像这样。使用“ord”函数将每个字符转换为int:

>>> [ord(c) for c in '\x0f\x07UUU']
[15, 7, 85, 85, 85]

签出binascii.hexlify。根据描述:

Return the hexadecimal representation of the binary data. Every byte of data is converted into the corresponding 2-digit hex representation. The resulting string is therefore twice as long as the length of data.

例如:

>>> import binascii
>>> binascii.hexlify('\x0f\x07UUU')
'0f07555555'

对于返回十六进制:

>>> data = binascii.hexlify('\x0f\x07UUU')
>>> ['0x' + data[i:i+2] for i in range(0, len(data), 2)]
['0x0f', '0x07', '0x55', '0x55', '0x55']

相关问题 更多 >

    热门问题