arul's code
free code snippets

Convert Binary Numbers to Decimal and vice-versa

Convert Binary to Decimal and vice-versa

To convert a binary number to decimal base, use unpack and pack.

my $binnum = '1101'; # binary number 
my $decnum = unpack("N", pack("B32", substr('0'x32.$binnum, -32)));
print "$binnum = $decnum \n";

To convert a decimal number to binary, use unpack.

my $decnum = 25; # decimal number
my $binnum = unpack("B32", pack("N", $decnum)); # in binary
$binnum =~ s!^0+(?=\d)!!;
print "$decnum = $binnum \n";

Share this

Last Updated: Posted on 07 Feb 2015