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 http://icfun.blogspot.com/2009/04/algorithm-bitwise-operation-to-convert.html

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";
else
output = output + "0";
end

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

print output;
end


TO use the code
binary_2_decimal(4294967290);


The output will be
11111111111111111111111111111010

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.




2 comments:

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.