Rajind Ruparathna
Rajind Ruparathna

Reputation: 2255

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?

Upvotes: 1

Views: 6136

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1502176

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);
    }

}

Upvotes: 5

matsev
matsev

Reputation: 33779

As of Java 7, you can use binary literals directly in your code. However, note that these are of type byte, short, int or long (and not String).

int x = 0b111;

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

Integer.decode cannot parse binary, see API. But octal work fine, example:

int i = Integer.decode("011");

Upvotes: 0

Related Questions