代码:
1 import java.util.List; 2 import java.util.ArrayList; 3 import java.util.Scanner; 4 public class Transformation { 5 public static void main(String[] args)throws Exception { 6 String a; 7 boolean b; 8 Scanner in=new Scanner(System.in); 9 10 System.out.println("请输入IP地址或32位2进制数"); 11 a=in.next(); 12 if((b=a.matches("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))) { 13 System.out.println("IP地址转2进制"); 14 String[] array = a.split("\."); 15 /* for ( int i=0; i < array.length; i++) { 16 System.out.println(array[i]); 17 }*/ 18 int[] intTemp = new int[array.length]; 19 for (int i=0; i <array.length; i++) 20 { 21 intTemp[i] = Integer.parseInt(array[i]); 22 } 23 for (int i=0;i<intTemp.length ;i++) 24 { 25 int c =intTemp[i]; 26 String binaryString = Integer.toBinaryString(c);//1111 27 int binaryInt = Integer.parseInt(binaryString);//1111 28 System.out.print(String.format("%08d",binaryInt));//00001111 29 } 30 } 31 else if(b=a.matches("\d{32}")) { 32 System.out.println("2进制转iP地址"); 33 /* 34 for(int i = 0; i < a.length(); i++){ 35 arr[i] = a.substring(0,8); 36 result.add(tmp) 37 a= a.substring(8); 38 // System.out.println(arr[i]);*/ 39 List<String> result = new ArrayList<String>(); 40 int iPos = 0; 41 int iLen = a.length(); 42 while(iLen>=8){ 43 String tmp = a.substring(0, 8); 44 result.add(tmp); 45 a= a.substring(8); 46 iLen = a.length(); 47 } 48 for(String st:result){ 49 50 System.out.print(Integer.parseInt(st,2)); 51 52 System.out.print("."); 53 54 } 55 56 57 } 58 59 60 else { 61 System.out.println("非法的输入!!!!"); 62 63 } 64 } 65 66 } 67