Possible Duplicate:
Xor of string in ruby
I would like to make a XOR calculation between two strings.
irb(main):011:0> a = 11110000
=> 11110000
irb开发者_如何学Go(main):014:0> b = 10111100
=> 10111100
irb(main):015:0> a ^ b
=> 3395084
I would like to do this: "hello" ^ "key"
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 isn't the result you want, then you need to be explicit about how you want to perform the calculation, or what result you expect.
- convert both strings to byte arrays (take care with the character encoding, not everything can be represented with ASCII)
- pad the shorter array with zeroes, so that they're both same size
- for n from 0 to array size: XOR firstarray[n] with secondarray[n], probably store the result to result array
- convert result byte array back into a string
精彩评论