Skip to main content
Perl

Using PERL to convert decimal IP Address to binary

By October 7, 2013September 12th, 2022No Comments


DANGER Geek Alert

So you would like to display an IPv4 address in its binary form. Don’t ask us why but some of us have a a habit, lets just leave it at that 🙂

Using PERL 5.6 and higher it is easy using the function sprintf. You can always check the version of perl you are using with:

perl -v

To start with we will work with just one number to convert and then we can move to the full 4 octets of a dotted decimal address:

 

#!/usr/bin/perl
my $dec = sprintf("%b",$ARGV[0]);
print "$decn";

The shebang tells the system to run the script with perl. We sent up a local variable $dec from the output of sprintf. The %b tells us to convert the first argument passed through to the script to binary. The 3rd and final line prints the the binary output, $dec, with a new line n. Running the script as follow:

./dec2bin 255

And we should have 11111111 as the output.

If we run a smaller number though lets take 33, so

./dec2bin 33

We have only 6 numbers 100001. If we want to keep the 8 bits of each octet including the leading zeros we modify the sprintf statement a little. We change from “%b” to “%08b”

my $dec = sprintf("%08b",$ARGV[0]);

Now we can see that we do not strip the leading zeros and will allow the full 8 bits in the octet. Now we have the script working for one number we can pass 4 numbers representing the IP Address through to a modified script.

#!/usr/bin/perl
my $octet1 = sprintf("%08b",$ARGV[0]);
my $octet2 = sprintf("%08b",$ARGV[1]);
my $octet3 = sprintf("%08b",$ARGV[2]);
my $octet4 = sprintf("%08b",$ARGV[3]);
print "$octet1.$octet2.$octet3.$octet4n";

We now have 4 variables to represent each octet and then we print the converted octets separated with dots as per the IPv4 standard.