Jimmy Donovan
Jimmy Donovan

Reputation: 31

Interpret str as hex character sequence

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

Answers (2)

Brad Solomon
Brad Solomon

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

Alex Jadczak
Alex Jadczak

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

Related Questions