代码:
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
public class Transformation {
public static void main(String[] args)throws Exception {
String a;
boolean b;
Scanner in=new Scanner(System.in); System.out.println("请输入IP地址或32位2进制数");
a=in.next();
if((b=a.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"))) {
System.out.println("IP地址转2进制");
String[] array = a.split("\\.");
/* for ( int i=0; i < array.length; i++) {
System.out.println(array[i]);
}*/
int[] intTemp = new int[array.length];
for (int i=0; i <array.length; i++)
{
intTemp[i] = Integer.parseInt(array[i]);
}
for (int i=0;i<intTemp.length ;i++)
{
int c =intTemp[i];
String binaryString = Integer.toBinaryString(c);//
int binaryInt = Integer.parseInt(binaryString);//
System.out.print(String.format("%08d",binaryInt));//
}
}
else if(b=a.matches("\\d{32}")) {
System.out.println("2进制转iP地址");
/*
for(int i = 0; i < a.length(); i++){
arr[i] = a.substring(0,8);
result.add(tmp)
a= a.substring(8);
// System.out.println(arr[i]);*/
List<String> result = new ArrayList<String>();
int iPos = 0;
int iLen = a.length();
while(iLen>=8){
String tmp = a.substring(0, 8);
result.add(tmp);
a= a.substring(8);
iLen = a.length();
}
for(String st:result){ System.out.print(Integer.parseInt(st,2)); System.out.print("."); } } else {
System.out.println("非法的输入!!!!"); }
} }