Question

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?

Was it helpful?

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)> 

OTHER TIPS

Here's a slightly more sophisticated snippet (as compared to Ryan's).

a1 = [0,0,1,0]
a2 = [0,1,0,1]

def convert a
  a.reverse.each.with_index.reduce(0) do |memo, (val, idx)|
    memo |= val << idx
  end
end

convert a1 # => 2
convert a2 # => 5
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top