Creating an xor checksum of all bytes in a hexadecimal string In Python

When I tried to contact a sound processing device called the BSS London Blu-80, I found that I needed to send a checksum created using an Xoring message. A starting example of a message would be the following:

0x8d 0x1e 0x19 0x1b 0x83 0x00 0x01 0x01 0x00 0x00 0x00 0x4b 0x00 0x00 0xc2 

If 0xc2 is the correct checksum for this message.

"The checksum is a one-byte exclusive or (xor) of all bytes in the message body."

The body of the message is higher minus the checksum.

The code I'm trying to execute is:

 packet = '0x8d 0x1e 0x19 0x1b 0x83 0x00 0x01 0x01 0x00 0x00 0x00 0x4b 0x00 0x00' xor = 0 i = 0 while i < len(packet): xor = xor ^ ord(packet[i]) i += 1 >>print xor 46 >>print hex(xor) '0x2e' 

Obviously, I’m doing something wrong, and I don’t quite understand it. Any help would be appreciated.

Thanks!

+5
source share
2 answers

You declared packet as a printable representation of a message:

 packet = '0x8d 0x1e 0x19 0x1b 0x83 0x00 0x01 0x01 0x00 0x00 0x00 0x4b 0x00 0x00' 

therefore, your current message is not [0x8d, 0x1e, ..., 0x00] , but ['0', 'x', '8', 'd', ..., '0'] . So, the first step is to fix it:

 packet = '0x8d 0x1e 0x19 0x1b 0x83 0x00 0x01 0x01 0x00 0x00 0x00 0x4b 0x00 0x00' packet = [chr(int(x, 16)) for x in packet.split(' ')] 

Or you could consider coding to be β€œright” from the start:

 packet = '\x8d\x1e\x19\x1b\x83\x00\x01\x01\x00\x00\x00\x4b\x00\x00' 

At this point, we can xor a member by member:

 checksum = 0 for el in packet: checksum ^= ord(el) print checksum, hex(checksum), chr(checksum) 

the checksum that I get is 0x59 , not 0xc2 , which means that you either calculated the wrong one or the original message is not the one you specified.

+6
source

8-bit checksum Solution

r = hex (0x37 ^ 0x37 ^ 0xA0 ^ 0x00 ^ 0x07 ^ 0x63 ^ 0x80 ^ 0x8A ^ 0x05 ^ 0x0C) [2:]. Top ()

R

'C7'

0
source

Source: https://habr.com/ru/post/1205313/


All Articles