问题
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 1
s and 0
s 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