1

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?

1
  • What would you do to do the same the other way round? input.to_s(2).each_char.map { |c| c == '1' } isn't cutting it for huge numbers. Commented Nov 17, 2022 at 15:27

2 Answers 2

6

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)> 
Sign up to request clarification or add additional context in comments.

Comments

1

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

4 Comments

Question: does the usage of .reverse instead of .reverse! make a difference? If I understood correctly, the first one should consume double the memory, right
@Cadoiz reverse! mutates the original array. This has many consequences. One of which is if you convert the same array twice, you'll get different results. convert(a1); convert(a1)
@Cadoiz: but! instead of reverse.each, we can use reverse_each which does not build a temp array and does not touch the original array.
Especially the latter is great knowledge for me. It's unfortunately not there for my ancient linux, but it definitely is for ruby >2.6.10. I don't know how to find out earlier compatibility.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.