Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an integer into a Binary Array..

Can someone give the simplest solution to convert an integer into a Array of Integer representing its relevant 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?

like image 284
Rakesh Avatar asked Dec 21 '22 19:12

Rakesh


2 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 could avoid the call to Math.log2 by calculating successive powers of 2 until that power was too big:

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 verbose, but faster

like image 176
Frederick Cheung Avatar answered Jan 02 '23 23:01

Frederick Cheung


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 a final .reverse if you would like to see the values in descending order, of course.

like image 23
Ray Toal Avatar answered Jan 02 '23 22:01

Ray Toal