【问题标题】:how to convert binary strings longer than 9 characters to integers?如何将长度超过 9 个字符的二进制字符串转换为整数?
【发布时间】:2016-07-21 15:22:25
【问题描述】:

我正在开发一个程序,我正在尝试使用以下代码将二进制字符串转换为整数:

int x = Integer.parseInt(arrayList.get(count), 2);
//arrayList is a collection of 30 character binary strings
//count is an incrementing integer used to choose which string to use while inside of a while loop

我已经使用诸如“001010”之类的字符串测试了该程序,但是使用诸如“100000110000010100001111010110”之类的较大字符串可以编译,但是终端输出给我一个错误:

"@ java.lang.NumberFormatException.forInputString(NumberFormatException.java:(line number))

我该如何解决这个问题?

【问题讨论】:

  • 我会尝试使用longBigInteger
  • 编辑:试过'long decimalValue = Long.parseLong(arrayList.get(count), 2); '返回同样的错误
  • 9二进制数字长多少?
  • 在我的例子中,我的字符串是 30 位二进制

标签: java binary converter


【解决方案1】:

尝试Long.parseLong 方法而不是Integer.parseInt

【讨论】:

    【解决方案2】:

    你可以试试java.math.BigInteger

    String bin = "100000110000010100001111010110";
    BigInteger bi = new BigInteger(bin, 2);
    System.out.println(bi);
    

    输出:

    549536726
    

    您也可以使用Long.valueOf() 进行操作。但是,使用 Long 您的二进制字符串最长可达 63 位,而使用 BigInteger 的长度可以是任意多位。

    String bin = "100000110000010100001111010110";
    long biLong = Long.valueOf(bin, 2);
    System.out.println(biLong);
    

    【讨论】:

      猜你喜欢
      • 2018-01-11
      • 2012-02-27
      • 1970-01-01
      • 2012-08-16
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多