Converting python2 byte/string encoding to python3

巧了我就是萌 提交于 2019-12-14 02:26:16

问题


I'm communicating over a serial port, and currently using python2 code which I want to convert to python3. I want to make sure the bytes I send over the wire are the same, but I'm having trouble verifying that that's the case.

In the original code the commands are sent like this:

serial.Serial().write("\xaa\xb4" + chr(2))

If I print "\xaa\xb4" in python2 I get this: ��.
If I print("\xaa\xb4") in python3 I get this: ª´

Encoding and decoding seem opposite too:

Python2: print "\xaa".decode('latin-1') -> ª
Python3: print("\xaa".encode('latin-1')) -> b'\xaa'

To be crude, what do I need to send in serial.write() in python3 to make sure exactly the same sequence of 1s and 0s are sent down the wire?


回答1:


Use a bytes sequence.

ser.write(b'\xaa\xb4')


来源:https://stackoverflow.com/questions/46742787/converting-python2-byte-string-encoding-to-python3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!