0

Well, I was bored so I wanted to make a Binary>Decimal Converter. I set the upper limit of my converter to be a 30-bit number (1073741823) or (0111111111111111111111111111111). The problem I am having is that when I try to parse 111111111111111111111111111111, I get a NumberFormatException. Here is some code:

This code is responsible for checking if the String is a number, than parsing it into an int.

if (checkNumber(input)) {
        try {
        number = Integer.parseInt(input);
        } catch (NumberFormatException ex) {
            log(ex.getMessage());
        }
    } else {
        toDecimal();
    }

Here is the actual boolean for checking the String.

private static boolean checkNumber(String input) {
    for (char c : input.toCharArray()) {
        if (!Character.isDigit(c)) {
            return false;
        }
    }

    return true;
}

This is the output of the NumberFormatException:

java.lang.NumberFormatException: For input string: "111111111111111111111111111111"

I just don't understand why Java would throw that error. Any ideas?

Integer.parseInt(String, 2); was the correct answer.

4

4 Answers 4

2

Because Integer.parseInt(String) defaults to base 10.

You need to use Integer.parseInt(String, int) and specify the correct radix for the value you're trying to parse. For binary (base 2) that would be 2

int value = Integer.parseInt("00010010", 2);
Sign up to request clarification or add additional context in comments.

Comments

0

Size of integer in Java is -2,147,483,648 to 2,147,483,647. Your input exceeds that.

You can try using long, the max value is 9,223,372,036,854,775,807.

Maybe you should look into using BigInteger.

EDIT: My bad, didnt notice you want to parse binary, should have read more carefully.

Comments

0

Because your string representation is not paring bits. It is parsing 30 base 10 digits, which certainly will not fit in an int data type. If you want to parse base 2, you need to pass in the radix parameter to parseInt

Comments

0

It is parsed as a decimal but you need it to be parsed as a binary. Mark it as a binary:

number = Integer.parseInt(input,2);

In http://ideone.com/G6dqj6 you'll get 1073741823 as expected

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.