0

I want to cast a string (binary digits) to an Integer like this:

Integer.parseInt("011000010110")

I always get an NumberFormatException. Is the number of digits too high?

1
  • 1
    It may look like binary, that is going to be interpreted as decimal (and too high). Commented Feb 7, 2014 at 20:42

2 Answers 2

8

Yes, the string "011000010110" is about 11 billion, which is higher than the maximum representable int, Integer.MAX_VALUE, 2,147,483,647. Try

Long.parseLong("011000010110")

Or, if you meant it as binary, pass a radix of 2 to parseInt:

Integer.parseInt("011000010110", 2)
Sign up to request clarification or add additional context in comments.

3 Comments

As OP says "binary digits", the second version sounds like the right choice. :-)
I´m confused. if I print the parseInt("binary",2) return the decimal value is printed. I wanted the binary digits just as an integer. Do you understand me? Just the "digits" as halraldK said, not the value.
In that case parse it to Long, just like the first example in the answer.
0

All of Java's number classes are base 10. However, I found these two options here:

working with binary numbers in java

The BitSet class, or a way to declare an int as a binary number (Java 7+). The latter may not work for you depending on how you're obtaining these numbers.

Comments

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.