Convert string to decimal. Java

Question:

There are lines like this:

0x16
012
0b10
62

You need to convert them to:

22
10
2
62 

accordingly, but when using Integer.parseInt(String, int) I get NumberFormatException , how to solve this problem?

Answer:

For example, you can write a function like this

private static int StringToInteger(String input)
    {
        if(input.startsWith("0x"))
        {   
            return Integer.parseInt(input.substring(2), 16);
        }
        else if(input.startsWith("0b"))
        {
            return Integer.parseInt(input.substring(2), 2);
        }
        else if(input.startsWith("0") && input.length() > 1)
        {
            return Integer.parseInt(input.substring(1), 8);
        }
        else
        {
            return Integer.parseInt(input);
        }
    }
Scroll to Top