Name158
Name158

Reputation: 17

How do I add two long strings containing binary digits in Java?

I've been trying to add two long strings of binaries using the Integer.parseInt method as radix 2. However, I don't believe that this works for long strings of binary numbers. Is there a better way to do this?

Upvotes: 0

Views: 83

Answers (2)

mjlowky
mjlowky

Reputation: 1223

You can use BigInteger with radix:

BigInteger decInt = new BigInteger("111111111111111111111111111111111001111",2);

Have a look at the documentation: http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#BigInteger(java.lang.String,%20int)

Upvotes: 1

yshavit
yshavit

Reputation: 43391

You can use BigInteger for this. The BigInteger(byte[]) constructor takes a byte array that's interpreted as a two's complement integer, and you can then use the add function to add the two. Keep in mind that add doesn't modify either of the objects, as BigIntegers are immutable. Instead, it returns a new object.

Upvotes: 0

Related Questions