I'm sending the bytestring 0x0F, 0x07, 0x55, 0x55, 0x55 from a PIC microcontroller.
Over the serial port with Python I am using the readlines() command in PySerial. 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. What would be a good way to format this back to 0x0F, 0x07, 0x55, 0x55, 0x55?
In Python 2, a bytestring (str) is a string of 8-bit characters, so it will look like that. Use the "ord" function convert each character to an int:
>>> [ord(c) for c in '\x0f\x07UUU']
[15, 7, 85, 85, 85]
Check out 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. 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']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.