线程“main”中出现异常java.lang.NumberFormatException输入字符串:基数2下的“x”[重复]

eufgjt7s  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(165)
    • 此问题在此处已有答案**:

java.lang.NumberFormatException: For input string: "10101010101010101010101010101010" [duplicate](3个答案)
20小时前关门了。
我试图解决一个问题。当我把字符串输入到Integer. parseUnsignedInt()方法时,我遇到了一个异常。我该如何修复。代码如下

public static void main(String[] args) {

        String a = "10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101";
        String b = "110101001011101110001111100110001010100001101011101010000011011011001011101111001100000011011110011";

        System.out.println(addBinary(a, b));

    }

    public static String addBinary(String a, String b) {

        int val1 = Integer.parseUnsignedInt(a, 2);
        int val2 = Integer.parseUnsignedInt(b, 2);


        return Integer.toBinaryString(val1 + val2);

    }

例外情况是;

Exception in thread "main" java.lang.NumberFormatException: For input string: "10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001101" under radix 2
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
    at java.base/java.lang.Long.parseLong(Long.java:711)
    at java.base/java.lang.Integer.parseUnsignedInt(Integer.java:850)
    at com.fsk.Main12.addBinary(Main12.java:17)
    at com.fsk.Main12.main(Main12.java:11)

我该怎么办?

8qgya5xd

8qgya5xd1#

该值对于unsigned int太大。您可以改用BigInteger。有关BigInteger的最大大小的详细信息,请参阅下面的StackOverflow answers

var value = new BigInteger("10100000100100110110010000010101111011011001101110111111111101000000101111001110001111100001", 2);
System.out.println(value);

预期产出:

3105986644253122716271174625

相关问题