使用 Long.parseLong() 将 base-2 数字(作为字符串)解析为 base-10 Long int 时出现 NumberFormatExcpetion

NumberFormatExcpetion while using Long.parseLong() to parse a base-2 number(as a string) to a base-10 Long int

所以我正在尝试翻转 long int 的位,我就是这样做的,但是我得到了 NumberFormatException。 我正在将它转换为 base-2 字符串并在左侧添加零以成为 32 字符,然后翻转位,然后将其转换回 base-10 的 long。

Long n =4L;
String bits = String.format("%32s", Long.toBinaryString(n)).replace(' ', '0');
bits = bits.replace("0", "3");
bits = bits.replace("1", "0");
bits = bits.replace("3", "1");
return Long.parseLong(bits.trim(), 10);

转换为基数 2 后的 4L:

00000000000000000000000000000100

翻转所有位后:,我得到这个:

Exception in thread "main" java.lang.NumberFormatException: For input string: "11111111111111111111111111111011"

怎么了?我检查了不可打印的字符,但没有,我还修剪了数字以防有任何额外的空格,我试图在最后添加 L 但没有任何效果,有什么问题吗?

我不能 100% 确定这是否是您要查找的内容。这会将二进制字符串转换为长字符串。 注意:我没有在方法中检查 0。您可能需要更改它以满足您的需要。

    public long stringBinaryToLong( final String binaryString) {
        if(binaryString == null) {
            return 0l;
        }
        // Check length for long on binary string. How many binary digits are the max length.
        // Determine this by taking log(base 2) for Long max.
        // log base 2 not available so use this technique. --> log_base2 (x) = log_base10 (x) / log_base10 (2)
        if( binaryString.length() > Math.ceil( Math.log10( (double) Long.MAX_VALUE ) / Math.log10( 2.0 ) ) ) {
            throw new IllegalStateException("string of binary digits exceeds max size for a Java long.");
        }
        double base = 2.0, power=0.0;
        long result = 0l;
        for(int index=binaryString.length() - 1; index > -1; index--) {
            if( binaryString.charAt(index) == '1') {
                result += Math.pow(base,  power);
            }
            power += 1.0;
        }
        return result;
    }

所以问题出在parseLong方法的radix参数上,radix是指定我要解析的字符串的基数,而不是parse方法的输出

所以整个问题都解决了:

return Long.parseLong(bits.trim(), 10);

有了这个:

return Long.parseLong(bits.trim(), 2);

现在,位串(parseLong 方法的输入)是基数参数中提到的基数 2