Subnet address from slash notation to dot notation

Few weeks back I attempted to write a program that converts subnet address in slash notation to dot notation. Though answers using if/switch statements came to my mind, I am not pretty convinced with those. I like to follow the KISS principle here. After struggling for some time with the help of my friend Sree came with the below piece of code


public void setSubnetMask(int slashNotation) {
try {
   byte[] ipaddress = new byte[4];
   for (int i = 0; i < ipaddress.length; i++, slashNotation -= 8){
      ipaddress[i] = (byte) ((255 << (8 - (slashNotation < 9 ? slashNotation: 8))) & 255);
   }
   InetAddress address = InetAddress.getByAddress(ipaddress);
   this.subnetMask = address.getHostAddress();
  } catch (UnknownHostException e) {
      e.printStackTrace();
      this.subnetMask = "";
  }
}

Hope you find this useful. Let us know if you have a simpler approach.

Question for readers :- How will you approach the problem to achieve the vice versa functionality, i.e. converting the subnet address from dot notation (255.255.255.0) to slash notation (/24)

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Furl

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: