Home >Backend Development >Python Tutorial >How to convert byte array to string using Python
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.
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''数据
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!