How to calculate XOR with offset?
I want to do a XOR calculation with different offset to list in calculation.
Example :
key = [0, 1, 0]
text = ["0", "1", "0", "1", "0", "1", "0", "1", "1", "1"]
the XOR calculation:
key[0] ^ text[0] ;
key[1] ^ text[1] ;
key[2] ^ text[2] ;
key[0] ^ text[3] ;
key[1] ^ text[4] ;
key[2] ^ text[5] ;
key[0] ^ text[6] ;
key[1] ^ text[7] ;
key[2] ^ text[8] ;
key[0] ^ tex开发者_运维知识库t[9] ;
How to do this ?
You can use Array#cycle
method to "cycle" your key as much as needed:
text.zip(key.cycle).map{|t,k| t.to_i ^ k}
# => [0, 0, 0, 1, 1, 1, 0, 0, 1, 1]
Ruby 1.9 has .cycle:
key = [0, 1, 0]
text = ["0", "1", "0", "1", "0", "1", "0", "1", "1", "1"]
key_looper = key.cycle
p text.map{|el|key_looper.next ^ el.to_i} #=> [0, 0, 0, 1, 1, 1, 0, 0, 1, 1]
精彩评论