java ip转换

代码仅供参考,没做任何异常处理..
public static void main(String[] args) {
String ip = "127.0.0.1";
String[] toArray = ip.split("\\.");
long ipToLong = 0L;
ipToLong = ((Long.parseLong(toArray[0])) << 24) + (Long.parseLong(toArray[1]) << 16) + (Long.parseLong(toArray[2]) << + (Long.parseLong(toArray[3]));
System.out.println("ipToLong: " + ipToLong);

StringBuilder sbIns = new StringBuilder();
sbIns.append(ipToLong >>> 24);
sbIns.append(".");
sbIns.append((ipToLong & 0x00FFFFFF) >>> 16);
sbIns.append(".");
sbIns.append((ipToLong & 0x0000FFFF) >>> ;
sbIns.append(".");
sbIns.append(ipToLong & 0x000000FF);
System.out.println("longToIp: " + sbIns.toString());

StringBuilder sb = new StringBuilder();
StringBuilder ipToBinary = null;
for(String ipNo : toArray){
ipToBinary = new StringBuilder();
String result = toBinary(Integer.parseInt(ipNo),ipToBinary);
sb.append(result);

}

System.out.println("binary: " + sb.toString());
}

private static String toBinary(int ip,StringBuilder sb){
int val = (ip >>> 1);
int mod = (ip % 2);
sb.append(mod);
if(val > 1){
toBinary(val, sb);
}else{
sb.append(val);
}

paddingZero(sb);
// sb.reverse();
char[] ch = sb.toString().toCharArray();
char[] reverse = new char[ch.length];
int length = (reverse.length - 1);
int reverseIdx = 0;
for(int i = length; i >= 0; i--){
reverse[reverseIdx++] = ch[i];
}

return (String.valueOf(reverse));
}

private static StringBuilder paddingZero(StringBuilder ipNodeBinary){
int length = ipNodeBinary.length();
int paddingZeroLength = (8 - length);
for(int i = 0; i < paddingZeroLength; i++){
ipNodeBinary.append("0");
}

return ipNodeBinary;
}

你可能感兴趣的:(java)