添加两个大二进制数

时间:2012-03-23 10:27:56

标签: java binary

我正在尝试添加两个更大的二进制数(即位数大于31)但由于获得NumberFormatException而停滞不前。下面是引发异常的行 -

Integer.parseInt(binaryNo, 2);

我的想法是首先将二进制数转换为integer,然后在使用integerInteger.toBinaryString(integerSum)转换为二进制后再加在一起。但是,当发生整数溢出时,它不适用于具有大于31的位的二进制数。请告诉我任何可以以优化方式(最短时间)执行大二进制数添加的方法。谢谢。

3 个答案:

答案 0 :(得分:9)

java.math.BigInteger。用以下内容构造它:

public BigInteger(String val,
                  int radix)

在这种情况下,您的基数是2.请注意,每个BigInteger都是不可变的,因此您执行的算术略有不同:

BigInteger i = new BigInteger(...);
Biginteger j = new BigInteger(...);

BigInteger sum = i.add(j); // neither i nor j are modified

答案 1 :(得分:3)

您可以改用java.math.BigInteger。它具有任意精度,可以处理任意基数(在你的情况下使用二进制文件,基数为2)并且应该进行相当好的优化。

答案 2 :(得分:1)

考虑使用java.math.BigInteger类:

BigInteger first=new BigInteger(binaryNo1, 2);
BigInteger second=new BigInteger(binaryNo2, 2);

BigInteger result=first.add(second);
String binResult=result.toString(2);