2011-05-23 87 views
3

可能重复:
Xor of string in rubyXOR两个字符串

我想提出两个字符串之间的XOR运算。

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

我想做到这一点:"hello"^"key"

+0

看看[红宝石字符串的异或](http://stackoverflow.com/q/348991/49186) – dexter 2011-05-23 12:17:39

+3

你必须学会​​如何使用SO。你一直在发送很多基本相同的问题(XOR和更多的XOR),但是你不会评论答案,你不会选择它们,你也不会提供任何反馈。有什么问题?例如,这里(http://stackoverflow.com/questions/5961720/how-to-calculate-xor-with-offset),你有这个问题几乎解决了,只是得到每个字符串的字节,而不是使用整数0/1。 – tokland 2011-05-23 12:34:12

+2

这不是链接问题的重复([348991](http://stackoverflow.com/questions/348991/xor-of-string-in-ruby)),而是另一个([5961720](http: /stackoverflow.com/questions/5961720/how-to-calculate-xor-with-offset)) – finnw 2011-05-24 00:23:46

回答

1
  1. 转换两个字符串转换为字节数组(请注意使用的字符编码,而不是什么都可以用ASCII表示)
  2. 垫短阵与零相同,因此它们都是相同的大小
  3. 对于n从0到数组大小:XOR firstarray [n]与secondarray [n],可能将结果存储到结果数组
  4. 结果转换成字节数组转换回字符串
12
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" 

如果这不是你想要的结果,那么你需要明确你想要如何进行计算,或者是什么导致你的期望。