将python2字节/字符串编码转换为python3 [英] Converting python2 byte/string encoding to python3
问题描述
我正在通过串行端口进行通信,目前正在使用我想转换为python3的python2代码。我想确保通过电线发送的字节是相同的,但是我无法验证是这种情况。
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))
如果我打印 \xaa\xb4
在python2中得到:^。
如果我在python3中 print( \xaa\xb4)
:ª´
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 aaxaa .decode('latin-1')
->ª
Python3: print( \xaa .encode('latin -1'))
-> b'\xaa'
Python2: print "\xaa".decode('latin-1')
-> ª
Python3: print("\xaa".encode('latin-1'))
-> b'\xaa'
成为粗略的说,我需要在python3中发送 serial.write()
来确保 1
s和 0
s是通过有线发送的吗?
To be crude, what do I need to send in serial.write()
in python3 to make sure exactly the same sequence of 1
s and 0
s are sent down the wire?
推荐答案
使用个字节
序列。
ser.write(b'\xaa\xb4')
这篇关于将python2字节/字符串编码转换为python3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!