Java - NumberFormatException. 将长二进制字符串转换为十进制

4
我想将二进制字符串转换为十进制。
public class HelloWorld{

     public static void main(String []args){

        System.out.println(Integer.parseInt("000011011111110111000001110000111110", 2));
     }
}

我遇到一个错误:

java.lang.NumberFormatException: For input string: "000011011111110111000001110000111110".

如何解决这个问题?

你尝试解析的值在 Java 中不是有效的整数。 - seenukarthi
为什么?在Java中不是一个有效的整数。 - phnmnn
如何将长二进制字符串转换为整数? - phnmnn
https://dev59.com/d2855IYBdhLWcg3wKxHc - itwasntme
尝试在一个方法中添加这行代码 int x = 000011011111110111000001110000111110;,读取错误信息,你就会知道为什么了。 - Zaid Malhis
3个回答

3
简短的解决方案 - 整数根本达不到那么高。那不是一个整数。 ParseInt()文档提到,您会收到一个字符串和一个基数,并获得转换的结果。然而,整数是4字节=32位,因此范围为-(2^31)2^31-1,而您的数字11011111110111000001110000111110实际上有32位长 - 这意味着它比最大值还要大。因此,该函数引发了NumberFormatException - 这不是int的有效值。

如果您想要修复它,我建议使用ByteBuffer,就像这里所描述的那样:

ByteBuffer buffer = ByteBuffer.wrap(myArray);
buffer.order(ByteOrder.LITTLE_ENDIAN);  // if you want little-endian
int result = buffer.getShort(); // use with a bigInteger instead. you could use any of the bytebuffer functions described in the link :)

1
然而,整数占用32个字节...? - TEK
我正在经历一个个人时刻,我认为自己在过去的5年里一直错了!:P - TEK

2
您可以使用BigInteger类并将数字存储为long:
BigInteger bigInt=new BigInteger("000011011111110111000001110000111110");
long a=bigInt.longValue();

您要存储的值对于 int 来说太大,不在该类型可容纳的范围内(-(2^31)2^31-1)。因此它会抛出 NumberFormatException。在这里使用 long 是一个合适的选择。


0

你可以使用Long.parseLong来处理你问题中的字符串,但是你可能会发现它也有一定的限制,所以你需要实现不同的逻辑。

你可以编写一个方法将二进制字符串转换为整数。

public static long binaryToInteger(String binaryString) {
    char[] chars = binaryString.toCharArray();
    long resultInt = 0;
    int placeHolder = 0;
    for (int i=chars.length-1; i>=0; i--) {
        if (chars[i]=='1') {
          resultInt += Math.pow(2,placeHolder);
        }
        placeHolder++;
    }
    return resultInt;
}

Math.pow(2, placeHolder) 可能返回错误的值,因为它返回 double 类型,而你将其转换为 int 类型。最好使用 1 << placeholder。https://dev59.com/TmPVa4cB1Zd3GeqP5GB6 - egor.zhdan
这是最有效的代码: 'long r=0; for (int i=0; i<chars.length; ++i) r=r<<1+chars[i]-'0'; return r` - krzydyn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接