XOR two lines

Possible duplicate:
Xor strings in ruby

I would like to do an XOR calculation between two lines.

irb(main):011:0> a = 11110000
=> 11110000
irb(main):014:0> b = 10111100
=> 10111100
irb(main):015:0> a ^ b
=> 3395084

I would like to do this: "hello" ^ "key"

+3
source share
2 answers
class String
  def ^( other )
    b1 = self.unpack("U*")
    b2 = other.unpack("U*")
    longest = [b1.length,b2.length].max
    b1 = [0]*(longest-b1.length) + b1
    b2 = [0]*(longest-b2.length) + b2
    b1.zip(b2).map{ |a,b| a^b }.pack("U*")
  end
end

p "hello" ^ "key"
#=> "he\a\t\u0016"

If this is not the result that you want, then you need to be explicit about how you want to perform the calculation or what result you expect.

+13
source
  • convert both strings to byte arrays (take care of character encoding, not everything can be represented using ASCII)
  • enter a shorter array with zeros so that they will be the same size
  • for n from 0 to array size: XOR firstarray [n] with secondarray [n] will probably store the result in an array of results
  • convert byte array of result back to string
+1
source

All Articles