【问题标题】:NumberFormatExcpetion while using Long.parseLong() to parse a base-2 number(as a string) to a base-10 Long intNumberFormatExcpetion 同时使用 Long.parseLong() 将 base-2 数字(作为字符串)解析为 base-10 Long int
【发布时间】:2022-02-02 13:10:35
【问题描述】:

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

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

转换为base 2后为4L:

00000000000000000000000000000100

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

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

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

【问题讨论】:

  • 为什么不Long.parseLong(bits.trim(), 2)
  • 因为我想把它转换回base 10,它在base-2中作为一个字符串(称为位)
  • @HibaHasan:10 没有描述方法的输出,它必须描述输入(即字符串在),所以你必须在这里使用, 2。除此之外,您还会遇到一个问题,因为long 是有符号的,并且具有 32 位数字和前导 1 的二进制数超出了有符号长整数的有效范围。
  • 你们都说得对,我认为基数是我需要的输出,但结果是输入

标签: java exception type-conversion base numberformatexception


【解决方案1】:

我不能 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;
    }

【讨论】:

    【解决方案2】:

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

    所以整个问题通过替换这个来解决:

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

    用这个:

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

    现在,位串(parseLong 方法的输入)的基数为 2,如 radix 参数中所述

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-14
      • 2018-05-03
      • 1970-01-01
      • 2015-08-09
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      相关资源
      最近更新 更多