Skip to content

Instantly share code, notes, and snippets.

@werbet
Created May 9, 2012 11:15
Show Gist options
  • Save werbet/2643813 to your computer and use it in GitHub Desktop.
Save werbet/2643813 to your computer and use it in GitHub Desktop.
Converting IPv4 address encoded as integer to string and back, in Java.
public static String integerToStringIP(int ip) {
return ((ip >> 24 ) & 0xFF) + "." +
((ip >> 16 ) & 0xFF) + "." +
((ip >> 8 ) & 0xFF) + "." +
( ip & 0xFF);
}
public static Long StringToIntIP(String addr) {
String[] addrArray = addr.split("\\.");
long num = 0;
for (int i=0;i<addrArray.length;i++) {
int power = 3-i;
num += ((Integer.parseInt(addrArray[i])%256 * Math.pow(256,power)));
}
return num;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment