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?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Maximii77
  • 93
  • 1
  • 8

2 Answers2

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)
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • 1
    As OP says "binary digits", the second version sounds like the right choice. :-) – Harald K Feb 07 '14 at 20:48
  • 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. – Maximii77 Feb 07 '14 at 21:40
  • In that case parse it to Long, just like the first example in the answer. – Zinglish Feb 08 '14 at 20:58
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.

Community
  • 1
  • 1
user1854994
  • 87
  • 2
  • 5