网络IP十进制与二进制的相互转换:
public class SubMaskBinaryDecimal {
public static void main(String[] args) {
//测试
System.out.println("十进制转二进制");
System.out.println(ipToBinary("255.255.255.128"));
System.out.println(ipToBinary("255.255.255.127"));
System.out.println(ipToBinary("192.168.1.64"));
System.out.println("二进制转十进制");
System.out.println(binaryToTenIp("11111111.11111111.11111111.10000000"));
System.out.println(binaryToTenIp("11111111.11111111.11111111.01111111"));
System.out.println(binaryToTenIp("11000000.10101000.00000001.01000000"));
}
//十进制ip转二进制
public static String ipToBinary(String ip){
String binary="";
String[] str = ip.split("\\.");
//循环提取"."之前的数字
for (int i = 0; i < str.length; i++) {
String s = str[i].toString();
//把"."之前的每一段的十进制数字转为二进制 并循环串起
binary+=addZero(Integer.toBinaryString(Integer.parseInt(s)))+"."; //把"."补充回去
}
//提取0到binary.length() - 1范围的二进制码(去掉最后的点)
String lastBinaryIp=binary.substring(0, binary.length() - 1);
//返回最终的ip
return lastBinaryIp;
}
//对最后的二进制进行补零,让每一段都够八位
public static String addZero(String binary){
switch (binary.length()){
case 7:
return "0"+binary;
case 6:
return "00"+binary;
case 5:
return "000"+binary;
case 4:
return "0000"+binary;
case 3:
return "00000"+binary;
case 2:
return "000000"+binary;
case 1:
return "0000000"+binary;
default:
return binary;
}
}
//二进制转十进制
public static String binaryToTenIp(String binary){
String ten="";
String[] str = binary.split("\\.");
for (int i = 0; i < str.length; i++) {
String s = str[i].toString();
//二进制转十进制
ten+=Integer.parseInt(s,2)+".";//把"."补充回去
}
//提取0到ten.length() - 1范围的二进制码(去掉最后的点)
String lastTen=ten.substring(0, ten.length() - 1);
//返回十进制ip
return lastTen;
}
}
//测试
十进制转二进制
11111111.11111111.11111111.10000000
11111111.11111111.11111111.01111111
11000000.10101000.00000001.01000000
二进制转十进制
255.255.255.128
255.255.255.127
192.168.1.64