Wednesday, April 29, 2009

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

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

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

print output

To use the function

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.

1 comment:

Anonymous said...

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


Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...