0
Problem
I’m performing a serial communication in which the checksum the message needs to be sent or verified upon receiving. This must be checked with a XOR logic, which returns an int number, given by the following function:
def XOR(hex):
b = 0
for a in hex:
b = a ^ b
return b
With the following example: x
is the device response, as shown below:
And y
are the data without STX ( X02), ETX ( x03) and checksum.
x = b'\x02\x02\x40\x0b\x00\x77\xc0\x00\x03\xfe'
y = x[1:-2]
The XOR()
of y
is 254
decimally or FE
in hexadecimal, which shows that the function XOR()
is correct.
Testing
By performing the same procedure when sending a message, you are generating an error, because the encoding returns 0xfe
with i = hex(254).encode()
or i = hex(XOR(y)).encode()
.
However, when entering the checksum manually with +b'\xfe'
the message is sent correctly.
With the following test program:
a=b'0xfe'
b=b'\xfe'
print(int.from_bytes(a, byteorder='big'),int.from_bytes(b, byteorder='big'))
The following string 813196901 254
is printed, that is to say with b'0xfe'
an error occurs when converting to Python.
Question
How I encode a number with the notation ' x' and not '0x'?