Rajind Ruparathna Rajind Ruparathna - 23 days ago 18
Java Question

Integer.decode(String s)

class Test{

public static void main(String Args[]){

Integer x;
x = Integer.decode("0b111");
System.out.println(x);
}
}


This doesn't work with the prefix 0 for binary and for octal with the prefix 0.
What is the correct way to do it?

Answer

Looking at the documentation for Integer.decode, I see no indication that binary should work. Octal should work though, with a prefix of just 0:

System.out.println(Integer.decode("010")); // Prints 8

You could handle a binary indicator of "0b" like this:

int value = text.toLowerCase().startsWith("0b") ? Integer.parseInt(text.substring(2), 2)
                                  : Integer.decode(text);

Complete sample code showing binary, octal, decimal and hex representations of 15:

public class Test {
    public static void main(String[] args) throws Exception {
        String[] strings = { "0b1111", "017", "15", "0xf" };
        for (String string : strings) {
            System.out.println(decode(string)); // 15 every time
        }
    }

    private static int decode(String text) {
        return text.toLowerCase().startsWith("0b") ? Integer.parseInt(text.substring(2), 2)
                                     : Integer.decode(text);
    }

}
Comments