整数与IP地址间的转换

来源:互联网 发布:java动态方法 编辑:程序博客网 时间:2024/05/04 07:55

package oj.test;

import java.math.BigInteger;
import java.util.*;

public class Demo11 {

 /**
  * @整数与IP地址间的转换 
  * 原理:ip地址的每段可以看成是一个0-255的整数,把每段拆分成一个二进制形式组合起来,然后把这个二进制数转变成
  * 一个长整数。
  * 举例:一个ip地址为10.0.3.193
  * 每段数字             相对应的二进制数
  * 10                   00001010
  * 0                    00000000
  * 3                    00000011
  * 193                  11000001
  * 组合起来即为:00001010 00000000 00000011 11000001,转换为10进制数就是:167773121,即该IP地址转换后的数字就是它了。
  * 的每段可以看成是一个0-255的整数,需要对IP地址进行校验
  */
 
 
 public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  String str1 = sc.nextLine();
  String str2 = sc.nextLine();
  
  str1 = strTOdec(str1);
  str2 = decTOstr(str2);
  
  System.out.println(str1);
  System.out.println(str2);
  
 }

 private static String decTOstr(String str2) {
  BigInteger big = new BigInteger(str2);  //十进制转二进制
  String temp = big.toString(2);
  //System.out.println(temp);
  
  
  if(temp.length()%8!=0){
   int n = 8-temp.length()%8;
   for(int i=0;i<n;i++){
    temp = "0"+temp;
   }
  }
  //System.out.println(temp);
  
  String[] s = new String[4];
  for(int i=0;i<4;i++){
   s[i] = temp.substring(0, 8);
   temp = temp.substring(8);
  }
  String re ="";
  for(int j=0;j<4;j++){
   BigInteger t = new BigInteger(s[j],2);
   re=re+t.toString()+".";
  }
  return re.substring(0, re.length()-1);
 }

 private static String strTOdec(String str1) {
  String[] s = str1.split("\\.");
  String temp = "";
  for(int i=0;i<4;i++){
   s[i] = Integer.toBinaryString(Integer.parseInt(s[i])); //10 1010
   s[i] = toEi(s[i]);
   temp = temp+s[i];
  }
  BigInteger big = new BigInteger(temp,2);  //二进制字符串转换为十进制
  
  return big.toString();
 }

 private static String toEi(String s) {
  while(s.length()!=8){
   s = "0"+s;
  }
  return s;
 }
}

0 0