简体   繁体   中英

Adding two large binary numbers

I am trying to add two larger binary numbers (ie 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.

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

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM