ravi
ravi

Reputation: 6328

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.

Upvotes: 1

Views: 2321

Answers (3)

Tomas Narros
Tomas Narros

Reputation: 13468

Consider using the java.math.BigInteger class:

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

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

Upvotes: 1

Joachim Isaksson
Joachim Isaksson

Reputation: 180897

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.

Upvotes: 3

Mike Kwan
Mike Kwan

Reputation: 24447

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

Upvotes: 9

Related Questions