Home > Backend Development > Python Tutorial > How to convert byte array to string using Python

How to convert byte array to string using Python

anonymity
Release: 2019-05-25 10:25:19
Original
7260 people have browsed it

Use python to develop serial port tools. The basic reading and writing of serial port data flow depends on bytearray, and the data we get from pyqt’s serial port is in string format, so we must consider how to convert these two types of data. , in order to correctly send and receive data.

How to convert byte array to string using Python

First consider receiving serial port data, then the format is bytearray, the following needs to be processed into string format to display:

#按string来显示,byarray代表接收到的数据
readstr = byarray.decode('utf-8')#这样就直接转换成str格式
 
#强制转换
readstr = str(byarray)#用这种方式得到的数据会带有b''字符
 
#将读取的数据按十六进制字符显示,能让我们直接看到最底层的数据格式
readstr = ' '.join(hex(x) for x in byarray)#这句能把byarray里的数据遍历一遍转换成hex格式,而且用空格相连
将string格式转换成bytearray:
#wrstr代表从串口读到的字符串
byarray = wrstr.encode() #得到b''数据
Copy after login

The above is the detailed content of How to convert byte array to string using Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template