3
我想提出两个字符串之间的XOR运算。
irb(main):011:0> a = 11110000
=> 11110000
irb(main):014:0> b = 10111100
=> 10111100
irb(main):015:0> a^b
=> 3395084
我想做到这一点:"hello"^"key"
我想提出两个字符串之间的XOR运算。
irb(main):011:0> a = 11110000
=> 11110000
irb(main):014:0> b = 10111100
=> 10111100
irb(main):015:0> a^b
=> 3395084
我想做到这一点:"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"
如果这不是你想要的结果,那么你需要明确你想要如何进行计算,或者是什么导致你的期望。
看看[红宝石字符串的异或](http://stackoverflow.com/q/348991/49186) – dexter 2011-05-23 12:17:39
你必须学会如何使用SO。你一直在发送很多基本相同的问题(XOR和更多的XOR),但是你不会评论答案,你不会选择它们,你也不会提供任何反馈。有什么问题?例如,这里(http://stackoverflow.com/questions/5961720/how-to-calculate-xor-with-offset),你有这个问题几乎解决了,只是得到每个字符串的字节,而不是使用整数0/1。 – tokland 2011-05-23 12:34:12
这不是链接问题的重复([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