Wednesday, April 29, 2009

Ruby: Convert a decimal number into binary using bitwise operation

Share at Facebook

I have already showed you how to convert a decimal number into binary using Bitwise operations at my post

Here is a small Ruby code, this will take a 32 bit positive integer number, and after applying the last posted bitwise algorithm, it will just print out the binary representation of the provided number. Here is the Ruby code using bitwise operations.

## takes a positive number less than 2^32-1
## prints it's binary format
def binary_2_decimal(int)

## constant = 10000000000000000000000000000000
const = 0x80000000;
output = "";

i = 0;
## for each bit
while( i < 32)

## if the bit is set, print 1
if( (int & const) != 0 )
output = output + "1";
output = output + "0";

## shift the constant using right shift
const = const >> 1;
i = i + 1;

print output;

TO use the code

The output will be

Once again, The bitwise operators those are used to implement the algorithm are Logical AND, and logical shift (right >>) operators. Hope this will help you to understand about bitwise operations too.


Abdelrahman said...

You can convert decimal to binary directly by using to_s(2) method.

>>> puts 5454.to_s(2)
>>> 1010101001110

Anonymous said...

Abdelraham is right.