Q:

Adding two large binary numbers

I am trying to add two larger binary numbers (i.e. number of bits are greater than 31) but stuck due to getting NumberFormatException. Below is the line which is throwing exception-
Integer.parseInt(binaryNo, 2);

My idea was to convert both binary numbers into integer first, then adding together after that convert integer to binary back using Integer.toBinaryString(integerSum). But it's not applicable for binary number having bits larger than 31 as integer overflow occurs. Please tell me any way which can perform large binary number addition in optimized way (minimum time). Thank you.

A:

java.math.BigInteger. Construct it with:
public BigInteger(String val,
                  int radix)

Your radix in this case is 2. Note that each BigInteger is immutable so you perform arithmetic slightly differently:
BigInteger i = new BigInteger(...);
Biginteger j = new BigInteger(...);

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

A:

You could just use java.math.BigInteger instead. It has arbitrary precision, can handle arbitrary base numbers (in your case with binaries, base 2) and should be fairly well optimized.

