Reputation: 5
I want to XOR two strings of bytes and I'm trying to figure out what is the difference between these two pieces of code, the last one works, but I dont understand why one does and the other doesn't. I've also tried with bytes object but doesn't work either.
resultado3 = bytearray(len(ab))
for byte1, byte2 in zip(ab, bb):
resultado3 += bytearray(byte1 ^ byte2)
resultado2 = bytes([ x^y for (x,y) in zip(ab, bb)])
Being my two inputs: ab = 1c0111001f010100061a024b53535009181c and bb = 686974207468652062756c6c277320657965 and the outputs when I print them: resultado2 = b"the kid don't play" and resultado3 = bytearray(b'\x00 ..... \x00') (all filled with zeros)
Upvotes: 0
Views: 350
Reputation: 2676
The reason is simple: bytearray(n)
returns a zero-initialized bytearray of length n
. So when you did resultado3 += bytearray(byte1 ^ byte2)
you are effectively concatenating all-null bytearray of some length to your resultado3
.
To achieve your intended purpose, use resultado3 += bytearray([byte1 ^ byte2])
instead (note the list of one element).
Upvotes: 1