Reputation: 31
I am working on developing a checksum function where 4 bytes are converted to a string of characters in hexadecimal (eg. '00ABCDEF') listed below:
packet = "004100ff"
checksum = 0
for el in packet:
checksum ^= ord(el)
print (hex(checksum))
Currently, the only way to obtain the correct checksum (0xbe) is to manually rewrite the string as packet = '\x00\x41\x00\xff' which cannot be done automatically.
How could I make python interpret the string as if each 2 characters were bytes in hexadecimal to perform the checksum?
Upvotes: 1
Views: 280
Reputation: 40918
How could I make python interpret the string as if each 2 characters were bytes in hexadecimal to perform the checksum?
Use bytes.fromhex()
to interpret the str
as a series of hex digits:
>>> packet = "004100ff"
>>> bytes.fromhex(packet)
b'\x00A\x00\xff'
Note also that iterating over bytes
will give you int
, so no need for ord()
any more:
>>> for el in bytes.fromhex(packet): print(el) # or list(bytes.fromhex(packet))
...
0
65
0
255
Upvotes: 1
Reputation: 582
If I understand your question correctly. This should work.
packet = "004100ff"
checksum = 0
bytes_string = [packet[i:i+2] for i in range(0, len(packet), 2)]
for byte_string in bytes_string:
checksum ^= int(byte_string, 16)
print(hex(checksum))
Upvotes: 1