How to XOR two strings in Python

How to XOR two strings in Python

Hi,
The following function is returning the result of hex() which returns a string.

def change_to_be_hex(s):
    return hex(int(s,base=16))

You should use the ^ operator on integers.

def change_to_be_hex(s):
    return int(s,base=16)
    
def xor_two_str(str1,str2):
    a = change_to_be_hex(str1)
    b = change_to_be_hex(str2)
    return hex(a ^ b)
print xor_two_str(12ef,abcd)

Im not sure though thats the result youre looking for. If you want to XOR two strings, it means you want to XOR each character of one string with the character of the other string. You should then XOR ord() value of each char or str1 with ord() value of each char of str2.

def xor_two_str(a,b):
    xored = []
    for i in range(max(len(a), len(b))):
        xored_value = ord(a[i%len(a)]) ^ ord(b[i%len(b)])
        xored.append(hex(xored_value)[2:])
    return .join(xored)
    
print xor_two_str(12ef,abcd)

Or in one line :

def xor_two_str(a,b):
    return .join([hex(ord(a[i%len(a)]) ^ ord(b[i%(len(b))]))[2:] for i in range(max(len(a), len(b)))])

print xor_two_str(12ef,abcd)

hex returns a string, so youre trying to xor two strings.

def change_to_be_hex(s):
   return int(s,base=16)

Should fix this.

How to XOR two strings in Python

when you initially return hex, like in change_to_be_hex, you explicitly convert it to int. you need to do that throughout your code to add something to it – so, change increment_hex to:

return (int(hex_n) + 1)

Leave a Reply

Your email address will not be published. Required fields are marked *