Java - NumberFormatException。将长二进制字符串转换为 dec

Java - NumberFormatException. Convert long bynary string to dec

我想将二进制字符串转换为十进制。

public class HelloWorld{

     public static void main(String []args){

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

我收到错误:

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

如何解决?

简短的解决方案 - Integers 只是不要那么高。那不是整数。

ParseInt() documentation mentions, you recieve a string and a radix, and get back the result of the convertion. However, integers are 4 bytes = 32 bits, and thus range from -(2^31) to 2^31-1, and your number - 11011111110111000001110000111110, is in fact 32 bits long - which means, it's bigger than the maximal value. Thus, the function throws this NumberFormatException - 这不是一个有效的整数值。

如果你想修复它,我会使用 ByteBuffer, like described here:

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 :)

您可以使用 BigInteger class 并将数字存储为 long:

BigInteger bigInt=new BigInteger("000011011111110111000001110000111110");
long a=bigInt.longValue();

您要存储的值对于 int 来说太大,并且不在类型 int 可以容纳的范围内(-(2^31)2^31-1) .所以它抛出 NumberFormatExceptionlong 是一个合适的选择。

您可以对问题中的字符串使用 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;
}