What do these 2 lines of code actually do?

Hello!
I don’t know Ruby but I need to understand how the input value is manipulated in the lines below.
I think that the input is converted to the sum of the values of its characters but the second line is confusing; does it take the final value of the sum and perform the bitwise operations or per iteration? Could you provide a simple explanation of the steps followed?

Thank you in advance!

input.to_s.each_char.inject(0) do |sum, ch|
(sum << 8) ^ (ch.ord) ^ (sum >> 4)

"100".to_s.each_char.inject(0) { |sum, ch| 
  p [sum,ch.ord] 
 (sum << 8) ^ (ch.ord) ^ (sum >> 4)
}

[0, 49]
[49, 48]
[12595, 48]
=> 3223587

ch.ord is the binary value of a character
^ is exclusive OR ( XOR) between 2 numbers
‘<< 1’ is shifting a (binary) number (mulltiply it by 2)
‘>> 1’ is right shifting a (binary) number (div it by 2)

the value of the last expression of the bloc is the new value of ‘sum’, and the value returned by inject().

sum << 8 is shift of one octet the current ‘sum’ value.
(ch.ord) ^ (sum >> 4) is XOR between number value of curent character XOR current sum divided by 16

"100".to_s.each_char.inject(0) { |sum, ch| 
  newsum= (sum << 8) 
  encoded_byte_value = (ch.ord) ^ (sum >> 4)
 (  newsum ^  encoded_byte_value  )
}

So the result is a bignum wich is a encryption of the string value of ‘imput’ data.
Which encryption ? that is the question :slight_smile:

1 Like

Thanks a lot for the explanation!
It is actually an approach of string hashing.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs