Python: Convert a decimal number into binary using bitwise operation

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

Lets implement the above algorithm using Python scripting. I have made a small python script that will take a 32 bit positive integer number, and it will print the binary representation of that decimal number into screen. Here is the Python function.

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

## constant = 10000000000000000000000000000000
const = 0x80000000

output = ""
## for each bit
for i in range(1,33):

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

## shift the constant using right shift
const = const >> 1

print output


To use the function
binary_2_decimal(4294967270)


The output will be : 11111111111111111111111111100110

At the function, I have just checked the value of each bit using Bitwise AND operator, and also switch from each bit using Bitwise Shift operator. You can change the bit number from 32 bit from 16, 8, or into 4 according to your need.

Comments

Anonymous said…
Nice, but the name of the function should be "decimal_2_binary", I would say...

Cheers!
Mac.