解析IP地址[Java]

题目描述

原理: ip地址的每段可以看成是- -个0-255的整数,把每段拆分成一个二进
制形式组合起来,然后把这个二进制数转变成
一个长整数。
举例:一个ip地址为10.0.3.193
每段数字
相对应的二进制数
10 00001010
0 00000000
3 00000011
193 11000001
组合起来即为: 00001010 00000000 00000011 11000001 ,转换为10进制
数就是: 167773121,即该IP地址转换后的数字就是它了。
本题含有多组输入用例,每组用例需要你将-个ip地址转换为整数、将一个
整数转换为ip地址。

代码如下

import java.util.*;
public class two {
	//将IP地址转换为十进制数
    public static long IPToDIP(String IP){
        String[] str = IP.split("\\.");
        int[] ret = new int[str.length];
        for(int i = 0;i < str.length;i++){
            ret[i] = Integer.parseInt(str[i]);
        }
        long sum = 0;
        int n = str.length;
        for(int i = 0;i < str.length;i++){
            sum += ret[i] * (long)Math.pow(2,8 * (n-1));
            n--;
        }
        return sum;
    }
    //将十进制数装换为IP地址
    public static String DIPToIP(long DIP){
        Stack<Integer> stack = new Stack<>();
        List<Integer> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        while(DIP >= 1){
            stack.push((int)(DIP%2));
            DIP /= 2;
        }
        while(!stack.isEmpty()){
            list.add(stack.pop());
        }
        int i = list.size()-1;
        int sum = 0;
        while(i >= 0){
            sum = 0;
            int count = 0;
            for(int j = 0;j < 8&&i >= 0;j++){
                sum += list.get(i--) * (int)Math.pow(2,count++);
            }
            stack.push(sum);
        }
        while(!stack.isEmpty()){
            sb.append(stack.pop());
            sb.append(".");
        }
        return sb.toString().substring(0,sb.toString().length()-1);
    }
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        while(scan.hasNext()){
            String IP = scan.next();
            long DIP = scan.nextLong();
            System.out.println(IPToDIP(IP));
            System.out.println(DIPToIP(DIP));
        }
    }
}


版权声明:本文为a13572259715原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。