Search code examples
rubyintegerdata-conversionoctetstring

How to convert an octet string to a number?


I am trying to convert an octet string into an Integer in Ruby.
For now I have this solution:

def octet_string_to_i(str)
  str.bytes.map { |v| format('%08b', v) }.join.to_i(2)
end

It feels like total overkill. I found other questions about converting it to a string but none about an Integer. Is there any way to achieve this without first going through a string as in my solution?


Example values and results:

foobar 112628796121458
barbaz 108170670399866
123456 54091677185334

Solution

  • Using the following code:

    str.bytes.reverse_each.with_index.sum {|elem, idx| elem << (idx * 8) }
    

    Basically, we reduce the bytes by adding them to a sum, shifting each byte to its proper position using their index. This avoids having to first convert to a string and back, and achieves the same result.

    Credit goes to Sergio Tulentsev for the code.