-8

I'm working with java, and I'm trying to play with numbers in different bases (2,8 and 10).

So, I'm asking this question to change a binary number in string format into number in base 10

such as 11000000101010000000000000111111/base 2

I tried Integer.parseInt(str,radix) however I got errors. exepetion ""Exception in thread "main" java.lang.NumberFormatException: For input string: "11000000101010000000000000111111" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source)

azdoud
  • 1,229
  • 9
  • 17
  • Maybe this helps http://stackoverflow.com/questions/8548586/adding-binary-numbers – RubioRic Mar 29 '16 at 11:33
  • i've used `Integer.parseInt()` it does not work any other ideas – azdoud Mar 29 '16 at 11:34
  • The answer that I pointed you not only just parses Integer, it parses specifying a radix. – RubioRic Mar 29 '16 at 11:48
  • It uses the same algorithm explained by Kevin Esche. – RubioRic Mar 29 '16 at 11:49
  • thank you too @RubioRic, yes it uses radix but when i used Integer.parseInt(str,radix) the SE throws me this exepetion ""Exception in thread "main" java.lang.NumberFormatException: For input string: "11000000101010000000000000111111" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) "" so i asked this question – azdoud Mar 29 '16 at 11:54
  • FWIW, I don't think this is off-topic. It may be a duplicate, though, of the question linked to by RubioRic. – Rudy Velthuis Mar 29 '16 at 16:18

1 Answers1

5

BigInteger provides a BigInteger(String,int) constructor, where you can define the radix. You could simply create two instances, one for the initial value, and one for the 1. Further on you´d just need to use BigInteger#add.

After this is done, there´s also a toString(radix) function for BigInteger, where you can display the result for a different radix.

public static void main(String[] args) {
    BigInteger base = new BigInteger("11000000101010000000000111111111", 2);
    BigInteger one = new BigInteger("1", 2);
    BigInteger result = base.add(one);
    System.out.println(result.toString(2));
}   

output

11000000101010000000001000000000
SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33