【问题标题】:how can i use biginteger to operate with binaries values [closed]我如何使用 biginteger 对二进制值进行操作 [关闭]
【发布时间】:2018-05-29 07:21:35
【问题描述】:

我正在使用 java,我正在尝试使用不同基数(2,8 和 10)的数字。

所以,我问这个问题是将字符串格式的二进制数更改为以 10 为底的数字

如11000000101010000000000000111111/base 2

我尝试了 Integer.parseInt(str,radix) 但是我得到了错误。 exepetion“”线程“main”中的异常java.lang.NumberFormatException:对于输入字符串:“11000000101010000000000000111111”在java.lang.NumberFormatException.forInputString(未知源)在java.lang.Integer.parseInt(未知源)在java.lang .Integer.parseInt(未知来源)

【问题讨论】:

  • 我用过Integer.parseInt() 它没有任何其他想法
  • 我指出你的答案不仅解析整数,它解析指定基数。
  • 它使用 Kevin Esche 解释的相同算法。
  • 也谢谢@RubioRic,是的,它使用基数,但是当我使用 Integer.parseInt(str,radix) 时,SE 向我抛出了这个 exepetion “”线程“main”中的异常 java.lang.NumberFormatException:对于输入字符串:“11000000101010000000000000111111”在 java.lang.Integer.parseInt(Unknown Source) 在 java.lang.Integer.parseInt(Unknown Source) 的 java.lang.NumberFormatException.forInputString(Unknown Source) “”所以我问了这个问题

标签: java binary biginteger


【解决方案1】:

BigInteger 提供了一个BigInteger(String,int) 构造函数,您可以在其中定义radix。您可以简单地创建两个实例,一个用于初始值,一个用于1。更进一步,你只需要使用BigInteger#add

完成此操作后,BigInteger 还有一个 toString(radix) 函数,您可以在其中显示不同基数的结果。

public static void main(String[] args) {
    BigInteger base = new BigInteger("11000000101010000000000111111111", 2);
    BigInteger one = new BigInteger("1", 2);
    BigInteger result = base.add(one);
    System.out.println(result.toString(2));
}   

输出

11000000101010000000001000000000

【讨论】:

  • 谢谢@Kevin,这正是我要找的东西
猜你喜欢
  • 2012-08-02
  • 2014-10-25
  • 2018-03-31
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
  • 1970-01-01
  • 1970-01-01
  • 2014-07-05
相关资源
最近更新 更多