XORing long strings opimization?

Noen not.available at na.no
Tue Nov 4 14:31:26 EST 2003


Peter Otten wrote:

> Noen wrote:
> 
> 
>>def XOR(s1,s2):
>>""" XOR string s1 with s2 """
>>output = ""
>># Argument check
>>if (type(s1) and type(s2)) != type(""):
>>raise TypeError, "Arguments are not strings"
>>if len(s1) != len(s2):
>>raise ValueError, "Size differs in strings"
>># Xoring
>>for c1 in s1:
>>for c2 in s2:
>>output += chr(ord(c1) ^ ord(c2))
>>return output
>>
>>This way is very slow for large strings.
>>Anyone know of a better and faster way to do it?
> 
> 
> Before we start optimizing:
> 
> len(XOR(s1, s2)) == len(s1) * len(s2)
> 
> Bug or feature?
> 
> Peter

Oh, didnt notice that as I wrote it. Thanks...
Anyway, this is how it should be.

def XOR(s1,s2):
     """ XOR string s1 with s2 """
     output = ""
     # Argument check
     if (type(s1) and type(s2)) != type(""):
         raise TypeError, "Arguments are not strings"
     if len(s1) != len(s2):
         raise ValueError, "Size differs in strings"
     # Xoring
     for i in range(len(s1)):
         output += chr(ord(s1[i]) ^ ord(s2[i]))
     return output






More information about the Python-list mailing list