简体   繁体   English

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

[英]Converting PySerial Readline From String to Binary

I'm sending the bytestring 0x0F, 0x07, 0x55, 0x55, 0x55 from a PIC microcontroller.我正在从 PIC 微控制器发送字节串 0x0F、0x07、0x55、0x55、0x55。

Over the serial port with Python I am using the readlines() command in PySerial.通过带有 Python 的串行端口,我在 PySerial 中使用 readlines() 命令。 I receive:我收到:

['\x0f\x07UUU']

This does indeed correspond to the bytestring I sent, but it is formatted using what looks like a strange combination of hexadecimal and ASCII characters.这确实与我发送的字节串相对应,但它是使用十六进制和 ASCII 字符的奇怪组合进行格式化的。 What would be a good way to format this back to 0x0F, 0x07, 0x55, 0x55, 0x55?将其格式化回 0x0F、0x07、0x55、0x55、0x55 的好方法是什么?

In Python 2, a bytestring (str) is a string of 8-bit characters, so it will look like that.在 Python 2 中,字节串 (str) 是一个 8 位字符的字符串,所以它看起来像这样。 Use the "ord" function convert each character to an int:使用 "ord" function 将每个字符转换为 int:

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

Check out binascii.hexlify .查看binascii.hexlify According to the descritption:根据描述:

Return the hexadecimal representation of the binary data.返回二进制数据的十六进制表示。 Every byte of data is converted into the corresponding 2-digit hex representation.每个数据字节都转换为相应的 2 位十六进制表示。 The resulting string is therefore twice as long as the length of data.因此,生成的字符串是数据长度的两倍。

An example:一个例子:

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

For back to hex:回到十六进制:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM