python-3.xchecksumpython-bytearray

How to XOR Hex ByteArray Elements


I'm trying to XOR all the elements in a bytearray, and generate the resulting checksum value in Hex. Finally, l will append the result to form a new bytearray. Sorry, I'm rusty in python now.

XorMath = bytearray([0x50,0x021,0x45,0x53])

Xor1 = bytearray[0] ^ bytearray[1]
Xor2 = Xor1 ^ bytearray[2]
Xor3 = Xor2 ^ bytearray[3]

checksum = hex(Xor3)
new_array = XorMath.append(checksum)

print(new_array)

Any way to make this more elegant?


Solution

  • You can use functools.reduce to apply operator.xor cumulatively to the bytearray. The hex function converts an integer to a hex string, and should be called only when the value is to be displayed rather than stored in a bytearray:

    from operator import xor
    from functools import reduce
    
    XorMath = bytearray([0x50, 0x021, 0x45, 0x53])
    XorMath.append(reduce(xor, XorMath))
    print(list(map(hex, XorMath)))
    

    This outputs:

    ['0x50', '0x21', '0x45', '0x53', '0x67']