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) {
      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 ( 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


Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: