PHP: convert decimal to 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

I'll provide you a simple function that will take a 31 bit positive number, and it will print the corresponding binary number using the bitwise algorithm that I discussed before at my previous posting. Here is the function

## takes a positive number less than 2^31-1
## prints it's binary format
function binary2decimal($dec){

## constant = 1000000000000000000000000000000
$and = 0x40000000;

## for each bit
for( $i = 1; $i <= 31; $i++ ){
## if the bit is set, print 1

if( $dec & $and ){
print "1";
}
## if the bit is not set, print 0
else{
print "0";
}
## shift the constant using right shift
$and = $and >> 1;
}
print "\n";
}


Using the function
binary2decimal(2147483640);


The output of above code : 1111111111111111111111111111000

This time my function will work for only 31 bit positive number. Not more. But you can decrease the bit number into any other bit according to your need. I have just did a looping for 31 bits, and checked whether the position of each bit is set or not. If the position is set, it will print 1, other wise it will print 0.

The bit checking is made using Logical AND operation, and the bit shifting is made using Right shift(>>) operator.

Comments

Anonymous said…
print " Please enter the decimal number";
$x = ;
chomp($x);

$bin = "";

while ($x)
{
$bin = ($x%2).$bin;
$x = int ($x/2);
}
$bin = 0 if ($bin eq "");

print "Binary : $bin\n";