0

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?

4
  • By "binaries" do you mean you have byte[]s that represent the numbers you want to add? Commented Mar 13, 2017 at 3:06
  • An example of what I have is "10000011100" and "00000011000" but considerably longer and of the same number of characters. Commented Mar 13, 2017 at 3:07
  • Maximum you can have for Integer.parseInt with radix 2 is the binary of Integer.MAX_VALUE Commented Mar 13, 2017 at 3:14
  • Exactly how long is "long"? Commented Mar 13, 2017 at 3:22

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Could you provide an example of putting my strings into this byte[]?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.