Alexander
Alexander

Reputation: 490

Converting String binary literal into Integer [Java]

I was thinking something along the lines of:

public static void main(String[] args) {
    int i;
    String s = "0b00110001";
    i = Integer.decode(s);
    System.out.print(s);
}

Upvotes: 3

Views: 582

Answers (1)

Andy Turner
Andy Turner

Reputation: 140328

Strip off the leading 2 characters and use Integer.parseInt:

Integer.parseInt(s.substring(2), 2);

You probably need some check that it does actually start with 0b.

Upvotes: 4

Related Questions