views:

408

answers:

5

i would like to do bitwise exclusive or of words in python but xor of strings are not allowed in python . so how to do it ?

+6  A: 

You can't. Strings contain characters. Characters are not numeric types, and you cannot calculate their xor.

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

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

If you want to do this then a string is probably the wrong datatype to use in the first place.

Mark Byers
+1  A: 

Do you mean something like this:

s1 = '00000001'
s2 = '11111110'
int(s1,2) ^ int(s2,2)
Satoru.Logic
A: 

Below illustrates XORing string s with m, and then again to reverse the process:

>>> s='hello, world'
>>> m='markmarkmark'
>>> s=''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m))
>>> s
'\x05\x04\x1e\x07\x02MR\x1c\x02\x13\x1e\x0f'
>>> s=''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m))
>>> s
'hello, world'
>>>
Mark Tolonen
+1  A: 

Here is your string XOR'er, presumably for some mild form of encryption:

>>> src = "Hello, World!"
>>> code = "secret"
>>> xorWord = lambda ss,cc: ''.join(chr(ord(s)^ord(c)) for s,c in zip(ss,cc*100))
>>> encrypt = xorWord(src, code)
>>> encrypt
';\x00\x0f\x1e\nXS2\x0c\x00\t\x10R'
>>> decrypt = xorWord(encrypt,code)
>>> print decrypt
Hello, World!

Note that this is an extremely weak form of encryption. Watch what happens when given a blank string to encode:

>>> codebreak = xorWord("      ", code)
>>> print codebreak
SECRET
Paul McGuire
+3  A: 

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'
Duncan
I believe this is the answer that most probably corresponds to what the OP wanted to ask.
ΤΖΩΤΖΙΟΥ