From: Ken Bloom Date: 2007-01-30T00:10:06+09:00 Subject: Re: "a string".xor("another string") On Mon, 29 Jan 2007 05:28:59 +0900, Erik Veenstra wrote: > I want to do an XOR of two strings: > > "a string".xor("another string") > > It's not that hard to implement, but it's not fast either, > since it walks through the data string, byte-by-byte. > > Any ideas? For example: "It's memory-hungry!". Any solutions? > > gegroet, > Erik V. - http://www.erikveen.dds.nl/ > > ---------------------------------------------------------------- > > class String > def xor(other) > if other.empty? > self > else > a1 = self.unpack("c*") > a2 = other.unpack("c*") > > a2 *= 2 while a2.length < a1.length > > a1.zip(a2).collect{|c1,c2| c1^c2}.pack("c*") > end > end > end > > ---------------------------------------------------------------- I tried changing your code to work on machine words (on my x86) by using "I*" instead of "c*". The result wasn't any faster. I also tried class String def xor(other) ret=dup ret.length.times{|n| ret[n]^=other[n]} ret end end once again, the result wasn't any faster. If you want fast, your best bet is probably to write it in C. -- Ken Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/