Perl: 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

Now I'm giving an example using Perl script. The small Perl code will just print out the binary representation of a positive number less than 2^32 -1. Means its 32 bit. Here is the example

binary_2_decimal(4204967294);

## takes a positive number less than 2^32-1
## prints it's binary format
sub binary_2_decimal{
my $int = shift;

## constant = 10000000000000000000000000000000
my $and = 0x80000000;

## for each bit
for(1..32){
## if the bit is set, print 1
if( $int & $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";
}


The output will be of above code : 11111010101000101011010101111110

I have just used the bitwise AND and Bitwise Shift(Right >>) operator to implement the algorithm.

Once again for reminder, the above code will work for 32 bit unsigned integer number. if you want to reduce the bit from 32 to any other, just reduce the for loop accordingly.

Comments

jotr said…
shell> perl -e 'printf "%b", 4204967294'
Demon said…
Hey, thanks for that. But I was discussing about Bit-wise operations.
Brice Cox said…
Thanks for this, made the comparison of Cisco ACLs much faster than some of the other methods I tried.
Anonymous said…
is it safe to say this perl script should be called decimal_2_binary and not binary_2_decimal?? almost slipped on that ;)