开发者

XOR two strings [duplicate]

This question already has answers here: Closed 11 years ago.

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.


  1. convert both strings to byte arrays (take care with the character encoding, not everything can be represented with ASCII)
  2. pad the shorter array with zeroes, so that they're both same size
  3. for n from 0 to array size: XOR firstarray[n] with secondarray[n], probably store the result to result array
  4. convert result byte array back into a string
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜