rubybitarray

Ruby: Convert a bitarray to an integer


I am trying to convert a bit array, such as [0,0,1,0].to_i = 2 or [0,1,0,1].to_i = 5.

What possible ways are there to do this in Ruby?


Solution

  • Here's one way:

      [1] pry(main)> [0,0,1,0].join.to_i(2)
      => 2
      [2] pry(main)> [0,1,0,1].join.to_i(2)
      => 5
      [3] pry(main)>