简体   繁体   English

如何从字节转换为字符串?

[英]How to convert from bytes to string?

I am using OpenCV library in Python to detect faces and calculate the centre point of the rectangle(X,Y) formed around the face to control servos connected to an arduino. I converted it to bytes since python uses unicode, like this我正在使用 Python 中的 OpenCV 库来检测面部并计算面部周围形成的矩形(X,Y)的中心点以控制连接到 arduino 的伺服系统。我将其转换为字节,因为 python 使用 unicode,像这样

data = "X{0:f}Y{1:f}".format(xx, yy)
bdata = b'data'
arduino.write(bdata)

I have to recieve these bytes in arduino program via serial communication, and it is receiving.我必须通过串行通信在 arduino 程序中接收这些字节,它正在接收。 The problem is i can't decode it back to string so the program can read I have tried and searched as much as on google read so many forums but nothing I am beginner in this as I have mechanical engg background so a total noob.问题是我无法将其解码回字符串,因此程序可以读取我已经尝试并搜索了尽可能多的内容,就像在谷歌上阅读了这么多论坛一样,但我在这方面一无所知,因为我有机械工程背景,所以完全是菜鸟。 I dont even know if this possible.我什至不知道这是否可能。 thanks in advance!提前致谢!

bdata = b'data'

This is creating a string of four bytes, representing the characters d , a , t , a in ASCII encoding.这将创建一个包含四个字节的字符串,以 ASCII 编码表示字符data That's probably not what you meant!那可能不是你的意思!

What you should do instead is encode the data string into bytes using the encode function. This requires that you think about the encoding;您应该做的是使用encode function 将data字符串编码为字节。这需要您考虑编码; probably ASCII is fine for this situation, because you don't have any "special" characters:可能 ASCII 适合这种情况,因为您没有任何“特殊”字符:

bdata = data.encode('ascii')

As a general tip, it can be useful to experiment in the Python interpreter, for example:作为一般提示,在 Python 解释器中进行实验可能很有用,例如:

>>> xx = 4.3
>>> yy = 7.1
>>> data = "X{0:f}Y{1:f}".format(xx, yy)
>>> bdata = b'data'
>>> bdata
b'data'
>>> bdata = data.encode('ascii')
>>> bdata
b'X4.300000Y7.100000'

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

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