Friday, February 25, 2011

IP Address to Binary

When I was teaching myself subnetting some time ago, I wrote a perl script to assist in learning the conversion. There are many ways to do this but I wanted a method to help me learn to do the conversion in my head. This is why the subroutine is written out as collection of if than statements to represent the bits in the octet.
#!/usr/bin/perl
# use: ./ip2binary.pl 192.168.1.1
use strict;

my $ip = $ARGV[0];

if($ip =~ /\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b/) {
 my @binary;
 my @octets = split(/\./,$ip);

 foreach my $octet (@octets) {
  push (@binary, return_binary($octet));
 }

 print join(".",@binary) . "\n";
} else {
 print "$ip is not a valid IP\n";
}

exit;

sub return_binary {
 my $decimal = $_[0];
 my @binary;
 if($decimal >= 128) {
  $binary[0] = 1;
  $decimal -= 128;
 } else {
  $binary[0] = 0;
 }

 if($decimal >= 64) {
  $binary[1] = 1;
  $decimal -= 64;
 } else {
  $binary[1] = 0;
 }

 if($decimal >= 32) {
  $binary[2] = 1;
  $decimal -= 32;
 } else {
  $binary[2] = 0;
 }

 if($decimal >= 16) {
  $binary[3] = 1;
  $decimal -= 16;
 } else {
  $binary[3] = 0;
 }

 if($decimal >= 8) {
  $binary[4] = 1;
  $decimal -= 8;
 } else {
  $binary[4] = 0;
 }

 if($decimal >= 4) {
  $binary[5] = 1;
  $decimal -= 4;
 } else {
  $binary[5] = 0;
 }

 if($decimal >= 2) {
  $binary[6] = 1;
  $decimal -= 2;
 } else {
  $binary[6] = 0;
 }

 if($decimal >= 1) {
  $binary[7] = 1;
  $decimal -= 1;
 } else {
  $binary[7] = 0;
 }

 return join("",@binary);

}

No comments:

Post a Comment