Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do bitwise exclusive or of two strings in python?

I would like to perform a bitwise exclusive or of two strings in python, but xor of strings are not allowed in python. How can I do it ?

like image 374
Hick Avatar asked Apr 10 '10 08:04

Hick


People also ask

Can you XOR two strings in Python?

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.

Can I XOR two strings?

Approach: The idea is to iterate over both the string character by character and if the character mismatched then add “1” as the character in the answer string otherwise add “0” to the answer string to generate the XOR string.

How do you get XOR 2 numbers in Python?

The Bitwise XOR sets the input bits to 1 if either, but not both, of the analogous bits in the two operands is 1. Use the XOR operator ^ between two values to perform bitwise “exclusive or” on their binary representations. For example, when used between two integers, the XOR operator returns an integer.


2 Answers

You can convert the characters to integers and xor those instead:

l = [ord(a) ^ ord(b) for a,b in zip(s1,s2)] 

Here's an updated function in case you need a string as a result of the XOR:

def sxor(s1,s2):         # convert strings to a list of character pair tuples     # go through each tuple, converting them to ASCII code (ord)     # perform exclusive or on the ASCII code     # then convert the result back to ASCII (chr)     # merge the resulting array of characters as a string     return ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(s1,s2)) 

See it working online: ideone

like image 124
Mark Byers Avatar answered Sep 26 '22 23:09

Mark Byers


If you want to operate on bytes or words then you'll be better to use Python's array type instead of a string. If you are working with fixed length blocks then you may be able to use H or L format to operate on words rather than bytes, but I just used 'B' for this example:

>>> import array >>> a1 = array.array('B', 'Hello, World!') >>> a1 array('B', [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]) >>> a2 = array.array('B', ('secret'*3)) >>> for i in range(len(a1)):     a1[i] ^= a2[i]   >>> a1.tostring() ';\x00\x0f\x1e\nXS2\x0c\x00\t\x10R' 
like image 43
Duncan Avatar answered Sep 22 '22 23:09

Duncan