track ip addresses, phone numbers, etc

Convert Binary Numbers to Decimal and vice-versa

Published on 07 February 2015

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";

Created on 07 February 2015

Affiliate Disclosure: Some of the links to products on this blog are affiliate links. It simply means, at no additional cost to you, we’ll earn a commission if you click through and buy any product.