How to convert an integer to a binary array.

Can anyone give the simplest solution for converting the whole to an array of an array representing its corresponding binary digits.

Input => Output 1 => [1] 2 => [2] 3 => [2,1] 4 => [4] 5 => [4,1] 6 => [4,2] One way is : Step 1 : 9.to_s(2) #=> "1001" Step 2 : loop with the count of digit use / and % based on loop index, multiply with 2 store in a array 

Is there any other direct or better solution?

+4
source share
3 answers

Fixnum and Bignum have a [] method that returns the value of the nth bit. With this we can do

 def binary n Math.log2(n).floor.downto(0).select {|i| n[i] == 1 }.collect {|i| 2**i} end 

You can avoid the call in Math.log2 by computing sequential powers of 2 until this power is too large:

 def binary n bit = 0 two_to_the_bit = 1 result = [] while two_to_the_bit <= n if n[bit] == 1 result.unshift two_to_the_bit end two_to_the_bit = two_to_the_bit << 1 bit += 1 end result end 

more detailed but faster

+8
source

Here is a solution that uses Ruby 1.8. ( Math.log2 was added in Ruby 1.9):

 def binary(n) n.to_s(2).reverse.chars.each_with_index.map {|c,i| 2 ** i if c.to_i == 1}.compact end 

In action:

 >> def binary(n) >> n.to_s(2).reverse.chars.each_with_index.map {|c,i| 2 ** i if c.to_i == 1}.compact >> end => nil >> binary(19) => [1, 2, 16] >> binary(24) => [8, 16] >> binary(257) => [1, 256] >> binary(1000) => [8, 32, 64, 128, 256, 512] >> binary(1) => [1] 

Add the final .reverse if you want to see the values ​​in descending order, of course.

+3
source
 class Integer def to_bit_array Array.new(size) { |index| self[index] }.reverse! end def bits to_bit_array.drop_while &:zero? end def significant_binary_digits bits = self.bits bits.each_with_object(bits.count).with_index.map do |(bit, count), index| bit * 2 ** (count - index - 1) end.delete_if &:zero? end end 

Adapted and improved after these solutions found in comp.lang.ruby .

Some simple tests show that this solution is faster than algorithms involving base-2 logarithms or string manipulation, and slower than a direct bit of manipulation .

0
source

All Articles