首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NumberFormatExcpetion,同时使用Long.parseLong()将基-2数字(作为字符串)解析为基-10长int。

NumberFormatExcpetion,同时使用Long.parseLong()将基-2数字(作为字符串)解析为基-10长int。
EN

Stack Overflow用户
提问于 2022-02-02 13:10:35
回答 2查看 104关注 0票数 0

所以我试着翻转长整数的部分,这就是我要做的,但是我得到了NumberFormatException。我把它转换成一个基-2字符串,在左边添加零,变成一个32个字符,然后翻转位,然后把它转换回基-10的长。

代码语言:javascript
复制
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);

4L转换为基础2后:

0000000000000000000000000000100100

在翻转了所有的片段之后,我得到了这个:

代码语言:javascript
复制
Exception in thread "main" java.lang.NumberFormatException: For input string: "11111111111111111111111111111011"

怎么了?我检查了不可打印的字符,但没有,我也削减了数字,以防有任何额外的空格,我试图添加L在结尾,但没有工作,有什么问题吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-02-02 20:57:54

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

因此,整个问题得到了解决,代之以:

代码语言:javascript
复制
return Long.parseLong(bits.trim(), 10);

在这方面:

代码语言:javascript
复制
return Long.parseLong(bits.trim(), 2);

现在,如基参数中提到的那样,位串( parseLong方法的输入)的基数为2。

票数 0
EN

Stack Overflow用户

发布于 2022-02-02 14:47:34

我不能百分之百确定这是否是你想要的。这将将二进制字符串转换为long。注意:我没有在方法中检查0。你可能需要改变它以适应你的需要。

代码语言:javascript
复制
    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;
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70956236

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档