首页 > 试题广场 >

整数与IP地址间的转换

[编程题]整数与IP地址间的转换
  • 热度指数:210940 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

原理:ip地址的每段可以看成是一个0-255的整数,把每段拆分成一个二进制形式组合起来,然后把这个二进制数转变成
一个长整数。
举例:一个ip地址为10.0.3.193
每段数字             相对应的二进制数
10                   00001010
0                    00000000
3                    00000011
193                  11000001

组合起来即为:00001010 00000000 00000011 11000001,转换为10进制数就是:167773121,即该IP地址转换后的数字就是它了。

数据范围:保证输入的是合法的 IP 序列



输入描述:

输入 
1 输入IP地址
2 输入10进制型的IP地址



输出描述:

输出
1 输出转换成10进制的IP地址
2 输出转换后的IP地址

示例1

输入

10.0.3.193
167969729

输出

167773121
10.3.3.193
不使用位运算,直观暴力转换(命名简易 勿喷)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String input1 = in.nextLine();
        String input2 = in.nextLine();
        String[] strs = input1.split("\\.");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < strs.length; i++) {
            sb.append(tenToTwo(strs[i], 8));
        }
        System.out.println(Long.valueOf(sb.toString(),2).toString());
        // System.out.println(sb.toString());
        System.out.println(twoToTen(input2));
    }

    private static String tenToTwo(String str, int length) {
        long num = Long.parseLong(str, 10);
        StringBuilder sb = new StringBuilder();
        long temp = 0;
        while (num != 0) {
            temp = num % 2;
            num /= 2;
            if (temp == 0) {
                sb.append((char)('0' + 0));
            } else {
                sb.append((char)('0' + 1));
            }
        }
        int len = sb.length();
        if (len < length) {
            for (int i = 0; i < length - len; i++) {
                sb.append('0');
            }
        }
        return sb.reverse().toString();
    }

    private static String twoToTen(String str) {
        // 11100110  10010110  11010000  10011111
        // 00001010  00000011  00000011  11000001
        String totalStr = tenToTwo(str, 32);
        String[] strs = new String[4];
        for (int i = 0; i < 4; i++) {
            strs[i] = totalStr.substring(i * 8, i * 8 + 8);
            // String singleNum = twoToTen(strs[i]);
            String temp = strs[i];
            long num = Long.parseLong(temp, 2);
            strs[i] = String.valueOf(num);
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            sb.append(strs[i]);
            if (i != 3) sb.append('.');
        }
        return sb.toString();
    }
}


发表于 2024-03-23 19:13:26 回复(0)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;
        while ((str = br.readLine()) != null) {
            String[] ip = str.split("\\.");
            long num = Long.parseLong(br.readLine());
            //转10进制
            System.out.println(Long.parseLong(ip[0]) << 24 | Long.parseLong(ip[1]) << 16 |
                    Long.parseLong(ip[2]) << 8 | Long.parseLong(ip[3]));
            //转ip地址
            String sb = ((num >> 24) & 255) + "." + ((num >> 16) & 255) + "." +
                    ((num >> 8) & 255) + "." + (num & 255);
            System.out.println(sb);
        }
    }
}

发表于 2024-03-18 17:42:59 回复(1)
import java.util.Arrays;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String a = in.next();
            if (a.contains(".")) {
                String[] arr = a.split("\\.");
                String r = "";
                for (String t : arr) {
                    r += d2b(Integer.parseInt(t), 8);
                }
                System.out.println(b2d(r));
            } else {
                String t = d2b(Long.parseLong(a), 32);
                String r = "";
                for (int i = 0; i < t.length(); i += 8) {
                    r += b2d(t.substring(i, i + 8));
                    if (i + 8 < t.length()) r += ".";
                }
                System.out.println(r);
            }
        }
    }

    public static Long b2d(String b) {
        long sum = 0;
        for (int i = 0; i < b.length(); ++ i) {
            long t = (b.charAt(i) - '0');
            sum +=  t << (b.length() - i - 1);
        }
        return sum;
    }

    public static String d2b(long d, int s) {
        StringBuilder r = new StringBuilder();
        while (d != 0) {
            r.append(d % 2);
            d /= 2;
        }
        for (int i = r.length(); i < s; ++ i) r.append("0");
        r.reverse();
        return r.toString();
    }
}

发表于 2024-03-16 16:25:17 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String[] arr = in.nextLine().split("\\.");

        StringBuilder builder = new StringBuilder();
        for (String s : arr) {
            String num = Integer.toBinaryString(Integer.parseInt(s));
            while (num.length() < 8) {
                num = "0" + num;
            }
            builder.append(num);
        }
        long res = Long.parseLong(builder.toString(), 2);
        System.out.println(res);


        long n = in.nextLong();
        String s1 = Long.toBinaryString(n);
        while (s1.length() < 32) {
            s1 = "0" + s1;
        }
        StringBuilder builder1 = new StringBuilder();
        int len = s1.length() / 8;
        for (int i = 0; i < len; i++) {
            int n1 = Integer.parseInt(s1.substring(i * 8, i * 8 + 8), 2);
            builder1.append(i == len - 1 ? n1 : n1 + ".");
        }
        System.out.println(builder1.toString());

    }
}

编辑于 2024-03-09 17:10:34 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            String binary = in.nextLine();
            String decimalism = in.nextLine();
            String[] arr = binary.split("\\.");//通过"."切分IP地址

            //IP地址处理 遍历转换为二进制数,注意第一个数不满8位需要填充0
            String res = "";
            for (int i = 0; i < arr.length; i++) {
                String binaryString = Integer.toBinaryString(Integer.valueOf(arr[i]));
                String string = fill(binaryString, 8);
                res += string + binaryString;
            }
            //将整个二进制数直接转换为10进制数
            Long i = Long.parseLong(res, 2);
            System.out.println(i);

            //将十进制数转换为二进制,注意第一个数不满8位需要填充0
            String s = Long.toBinaryString(Long.parseLong(decimalism));
            String string = fill(s, 32);
            s = string + s;
            String res2 = "";
            //遍历8位8位转换 转换后凭借"."
            for (int j = 0; j < s.length(); j += 8) {
                int binaryInt = Integer.parseInt(s.substring(j, j + 8), 2);
                if (j < 24) {
                    res2 += binaryInt + ".";
                } else {
                    res2 += binaryInt;
                }
            }
            System.out.println(res2);
        }
    }
    //为二进制填充0直到32位
    private static String fill(String s, int x) {
        int length = s.length();
        String string = "";
        if (length < x) {
            int j = x - length;
            for (int i = 0; i < j; i++) {
                string += "0";
            }
        }
        return string;
    }
}

编辑于 2023-12-29 14:54:50 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String [] arr = in.nextLine().split("\\.");
        Long n = in.nextLong();
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < arr.length; i++){
            String s1 = Long.toBinaryString(new Long(arr[i]));
            String b = "0000000".substring(s1.length() - 1) + s1;
            sb.append(b);
        }
        System.out.println(Long.parseLong(sb.toString(), 2));
        String str = Long.toBinaryString(n);
        StringBuilder bStr = new StringBuilder(str);
        for(int i = 0; i < 32 - str.length(); i++) bStr.insert(0, '0');
        for(int i = 0; i < bStr.length(); i = i+8){
            String sub = bStr.substring(i , i + 8);
            if( i == 24)
                System.out.print(Long.parseLong(sub, 2));
            else
                System.out.print(Long.parseLong(sub, 2)+".");
        }
    }
}

发表于 2023-11-23 17:03:59 回复(0)
import java.util.*;
public class Main {
    public Long transformIp(String str) {
        String[] split = str.split("\\.");
        StringBuilder sb = new StringBuilder();
        for (String s : split) {
            String binaryStr = Integer.toBinaryString(Integer.parseInt(s));
            while (binaryStr.length() < 8) {
                binaryStr = "0" + binaryStr;
            }
            sb.append(binaryStr);
        }
        long num = Long.parseLong(sb.substring(sb.indexOf("1")), 2);
        return num;
    }

    public String unTransformIp(String num) {
        String binaryStr = Long.toBinaryString(Long.parseLong(num));
        while (binaryStr.length() < 32) {
            binaryStr = "0" + binaryStr;
        }
        ArrayList<String> arr = new ArrayList<>();
        for (int i = 0; i < binaryStr.length(); i += 8) {
            String sub = binaryStr.substring(i, i + 8);
            if (!sub.contains("1")) {
                arr.add("0");
            } else {
                String s = sub.substring(sub.indexOf("1"));
                arr.add(String.valueOf(Long.parseLong(s, 2)));
            }
        }
        String join = String.join(".", arr);
        return join;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String a = in.nextLine();
        String b = in.nextLine();
        System.out.println(new Main().transformIp(a));
        System.out.println(new Main().unTransformIp(b));
    }
}

发表于 2023-09-19 17:44:14 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s[]=new String[2];
        int l=0;
        while(in.hasNextLine()){
            s[l]=in.nextLine();
            l++;
        }

        String str[]=s[0].split("\\.");


        long num=Long.valueOf(str[0])*256*256*256+Long.valueOf(str[1])*256*256+
                Long.valueOf(str[2])*256+Long.valueOf(str[3]);
        System.out.println(num);
        long num1=Long.valueOf(s[1])/256/256/256;
        System.out.print(num1+".");
        long num2=(Long.valueOf(s[1])-num1*256*256*256)/256/256;
        System.out.print(num2+".");
        long num3=(Long.valueOf(s[1])-num1*256*256*256-num2*256*256)/256;
        System.out.print(num3+".");
        long num4=Long.valueOf(s[1])-num1*256*256*256-num2*256*256-num3*256;
        System.out.print(num4);
    }
}

发表于 2023-09-18 17:29:51 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String str = in.next();
            boolean IP = false;
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) == '.') {
                    IP = true;
                    break;
                }
            }
            if (IP) {
                System.out.println(toNumber(str));
            } else {
                System.out.println(toIP(str));
            }
        }
    }
    public static long toNumber(String str) {
        String[] split = str.split("\\.");
        long Number = 0;
        for (int i = 0; i < split.length; i++) {
            Number += (long)Math.pow(256, split.length - i - 1)*Long.parseLong(split[i]);
        }
        return Number;
    }
    public  static String toIP(String str) {
        String string = "";
        long num=Long.parseLong(str);
        int[] slice=new int[4];
        for (int i = 0; i < 4; i++) {
            slice[i]=(int)(num % 256);
            num=(int)(num/256);
        }
        for (int i = 0; i < slice.length; i++) {
            string+=slice[3-i];
            if (i<slice.length-1){
                string+=".";}
        }
        return string;
    }
}

发表于 2023-09-05 03:12:49 回复(0)
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringJoiner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line1 = br.readLine();
        String line2 = br.readLine();

        long number = Long.parseLong(line2);

        System.out.println(ipToNumber(line1));
        System.out.println(numberToIp(number));


    }

    /**
     * 将ip地址转换为10进制数字
     *
     * @param ip
     * @return
     */
    private static long ipToNumber(String ip) {
        // 拆分ip地址
        String[] split = ip.split("\\.");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < split.length; i++) {
            String s = split[i];
            // 字符串转换为十进制数字
            int num = Integer.parseInt(s);
            // 十进制转换为二进制
            String binaryString = Integer.toBinaryString(num);
            // 不足8位前面补0
            StringBuilder pre = new StringBuilder("00000000");
            String preBinary = pre.append(binaryString).toString();
            // 截取后8位
            String binary = preBinary.substring(preBinary.length() - 8);
            sb.append(binary);
        }

        // 拼接后将二进制字符串转换为十进制数字
        return Long.parseLong(sb.toString(), 2);
    }

    /**
     * 将十进制数字转换为ip地址
     * @param number
     * @return
     */
    private static String numberToIp(long number) {
        // 将数字转换为二进制
        String binaryString = Long.toBinaryString(number);
        // 不足32位补0
        StringBuilder pre = new StringBuilder("00000000000000000000000000000000");
        StringBuilder preBinary = pre.append(binaryString);
        // 截取最后32位
        String binary = preBinary.substring(preBinary.length() - 32);
        StringJoiner sj = new StringJoiner(".", "", "");

        // 每8位转换为十进制数字,拼接
        while (binary.length() > 0) {
            String sub = binary.substring(0, 8);
            int num = Integer.parseInt(sub, 2);
            sj.add(num + "");
            binary = binary.substring(8);
        }

        return sj.toString();
    }
}

发表于 2023-08-08 16:53:58 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case

            String str = in.nextLine();
            long a = ipToInteger(str);
            System.out.println(a);

            String str2 = in.nextLine();
            long b = Long.valueOf(str2);
            System.out.println(integerToIp(b));

        }
    }

    // 将ip地址转换为10进制的数
    public static long ipToInteger(String ip) {
        String[] tempStrArr = ip.split("\\.");

        String binaryStr = "";
        for (int i = 0; i < 4; i++) {
            String tempStr = Integer.toBinaryString(Integer.valueOf(tempStrArr[i]));
            while (tempStr.length() < 8) {
                tempStr = "0" + tempStr;
            }
            binaryStr += tempStr;
        }

        long sum = 0;
        for (int i = 0; i < 32; i++) {
            sum += (binaryStr.charAt(i) - '0') * Math.pow(2, 31 - i);
        }

        return sum;
    }

    // 将十进制的数转换为ip地址
    public static String integerToIp(long num) {
        String binaryStr = Long.toBinaryString(num);
        while (binaryStr.length() < 32) {
            binaryStr = "0" + binaryStr;
        }

        int[] ipArr = new int[4];
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 8; j++) {
                ipArr[i] += ((binaryStr.charAt(i * 8 + j) - '0') * Math.pow(2, 7 - j));
            }
        }

        String result = "";
        for (int i = 0; i < 4; i++) {
            if (i < 3) {
                result += (String.valueOf(ipArr[i]) + ".");
            } else {
                result += String.valueOf(ipArr[i]);
            }
        }

        return result;
    }

}

发表于 2023-07-06 09:53:47 回复(0)
String[] s = in.nextLine().split("\\.");
为什么一定要上面这样,用“.”就根本截不到?
比如:
String[] s = in.nextLine().split(".");





发表于 2023-05-31 17:19:30 回复(2)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String a = in.nextLine();
        String b = in.nextLine();
        String[] sp = a.split("\\.");
        long result = 0;
        for(int i = 0;i<sp.length;i++){
            Long num = Long.parseLong(sp[i]);
            result = (result <<8) | num;
        }
        System.out.println(result);
        Long nums = Long.parseLong(b);
        String bin = Long.toBinaryString(nums);
        while(bin.length() % 8 != 0){
            bin = "0"+bin;
        }
        StringBuilder bud = new StringBuilder();
        for(int i = 0;i<4;i++){
            String sub = bin.substring(i*8,(i+1)*8);
            int i1 = Integer.parseInt(sub,2);
            bud.append(i1);
            if(i!=3){
                bud.append(".");
            }
        }
        System.out.println(bud);
    }
}

发表于 2023-05-30 09:42:57 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        //IP
        String str1=in.nextLine();
        //十进制
        String str2=in.nextLine();
        String ip1Binary="";
        String tmp="";
        //IP转数字
        for(int i=0;i<str1.length();i++){
            tmp+=str1.charAt(i);
            if(str1.charAt(i)=='.'){
                ip1Binary+=toBinary(tmp.substring(0,tmp.length()-1));
                tmp="";
            }
            if(i==str1.length()-1){
                ip1Binary+=toBinary(tmp.substring(0,tmp.length()));
            }
        }
        //第一个结果
        Long num1=Long.valueOf(ip1Binary,2);
        //数字转IP
        String ip2Binary=Long.toBinaryString(Long.valueOf(str2));
        //转为2进制共32位
        while(ip2Binary.length()<32){
            ip2Binary="0"+ip2Binary;
        }
        ArrayList<Integer> list=new ArrayList<>();
        tmp="";
        for(int i=0;i<ip2Binary.length();i++){
            tmp+=ip2Binary.charAt(i);
            if((i+1)%8==0){
                list.add(Integer.valueOf(tmp,2));
                tmp="";
            }
        }
        String ip2="";
        for(int i=0;i<list.size();i++){
            ip2+=list.get(i)+".";
        }
        //第二个结果
        ip2=ip2.substring(0,ip2.length()-1);
        System.out.println(num1);
        System.out.println(ip2);
        
    }
    //数字转为2进制
    public static String toBinary(String str){
        String binary=Integer.toBinaryString(Integer.valueOf(str));
        while(binary.length()<8){
            binary="0"+binary;
        }
        return binary;
    }
}

发表于 2023-05-28 09:17:06 回复(0)
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        while (in.hasNext()) {
            String line = in.nextLine();
            String[] splits = line.split("\\.");
            long[] longs = new long[4];
            long result = 0;
            // ip 转 int
            if (line.contains(".")) {
                longs[0] = Long.parseLong(splits[0]);
                longs[1] = Long.parseLong(splits[1]);
                longs[2] = Long.parseLong(splits[2]);
                longs[3] = Long.parseLong(splits[3]);
                for (int i = longs.length - 1; i >= 0; i--) {
                    int shift = (longs.length - 1 - i) * 8;
                    result = result + (longs[i] << shift);
                }
                System.out.println(result);
            } else {
                // int 转 ip
                long input = Long.parseLong(splits[0]);
                longs[0] = input >> 24;
                longs[1] = (input & 0xff0000) >> 16;
                longs[2] = (input & 0xff00) >> 8;
                longs[3] = input & 0xff;

                System.out.printf("%d.%d.%d.%d\n", longs[0], longs[1], longs[2], longs[3]);
            }
        }
    }
}

发表于 2023-05-27 17:54:22 回复(0)
注意int可储存的最大值,注意从String转到Long的方法,注意"."的表示方法应该为“\\.”
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String a = in.nextLine();
            // System.out.println(a);
            Long b = in.nextLong();
            // System.out.println(b);
            String[] as = a.split("\\.");
            // System.out.println(as.length);
            if (as.length != 4) {
                continue;
            }

            // IP -> Long
            Long a0 = (Long) (Long.parseLong(as[0]) * 256 * 256 * 256);
            // System.out.println(a0);
            int a1 = Integer.parseInt(as[1]) * 256 * 256;
            int a2 = Integer.parseInt(as[2]) * 256;
            int a3 = Integer.parseInt(as[3]);
            
            // Long -> IP
            int b0 = (int) (b / 256 / 256 / 256);
            int b1 = (int) ((b / 256 / 256) % 256);
            int b2 = (int) ((b / 256) % 256);
            int b3 = (int) (b % 256);


            System.out.println(a0 + a1 + a2 + a3);
            System.out.println(b0 + "." + b1  + "." + b2 + "." + b3);
        }
    }
}


发表于 2023-05-26 12:01:11 回复(0)
看到这种,直接一个摁写
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String str = in.nextLine();
            if (str.indexOf(".") > -1) {
                // ip 转数值
                String[] ipNum = str.split("\\.");
                long count = (Long.parseLong(ipNum[0]) << 24) + (Long.parseLong(
                                ipNum[1]) << 16)
                            + (Long.parseLong(ipNum[2]) << 8) + Long.parseLong(ipNum[3]);
                System.out.println(count);
            } else {
                // 数据转ip
                long num = Long.parseLong(str);
                long ip1 = num / (int)Math.pow(2, 24);
                long ip2 = (num - ip1 * (int)Math.pow(2, 24)) / (int)Math.pow(2, 16);
                long ip3 = (num - ip1 * (int)Math.pow(2, 24) - ip2 * (int)Math.pow(2,
                           16)) / (int)Math.pow(2, 8);
                long ip4 = num - ip1 * (int)Math.pow(2, 24) - ip2 * (int)Math.pow(2,
                          16) - ip3 * (int)Math.pow(2, 8);
                System.out.println(ip1 + "." + ip2 + "." + ip3 + "." + ip4);
            }
        }
    }
}


发表于 2023-05-08 15:50:11 回复(0)

思路: 简单粗暴,不用多思考啥,就是二级制->十进制转换,十进制->二级制转换

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        while (input.hasNext()) {
            Object result;
            String line = input.nextLine();
            if (line.contains(".")) {
                result = ipConvertNumber(line);
            } else {
                result = NumberConvertIp(line);
            }
            System.out.println(result);
        }
    }

    private static String NumberConvertIp(String line) {
        long ipNumbers = Long.parseLong(line);
        String binaryString = Long.toBinaryString(ipNumbers);
        int supplementZeroLength = 32 - binaryString.length();
        StringBuilder stringBuilder = new StringBuilder();
        if (supplementZeroLength > 0) {
            for (int i = 0; i < supplementZeroLength; i++) {
                stringBuilder.append("0");
            }
        }
        stringBuilder.append(binaryString);
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < 32; i = i + 8) {
            result.append(Integer.parseInt(stringBuilder.substring(i, i + 8), 2))
            .append(".");
        }
        result.deleteCharAt(result.length() - 1);
        return result.toString();
    }

    private static long ipConvertNumber(String line) {
        String[] ipArr = line.split("\\.");
        StringBuilder numbers = new StringBuilder();
        for (String s : ipArr) {
            String toBinaryString = Integer.toBinaryString(Integer.parseInt(s));
            int supplementZeroLength = 8 - toBinaryString.length();
            if (supplementZeroLength >  0) {
                for (int i = 0; i < supplementZeroLength; i++) {
                    numbers.append("0");
                }
            }
            numbers.append(toBinaryString);
        }
        return Long.parseLong(numbers.toString(), 2);
    }
}
发表于 2023-05-06 07:47:24 回复(0)
我是上来就到用Java的Integer.parseInt()一顿转换,通过不到10个用例,可能是int数据类型装不下太大的整数,经过谷歌搜索,加上Java的文档说明:
- The value represented by the string is not a value of type `int`.
当整数字符串地大小超过int所容纳的数据范围,就会出错。
使用长整型的Long.parseLong(),成功解决问题。另外在使用String.split()时,如果以圆点分割,要加上转义符\\\\。
发表于 2023-05-02 21:59:56 回复(0)

问题信息

难度:
87条回答 56793浏览

热门推荐

通过挑战的用户

查看代码