0

Is there a way in Java SDK 1.8 to parse a String like "0b1" back to its integer value ?

I tried with Integer.parseInt but it fails.

Same question with this String "0b1111_1101" ?

Maybe there's something in Eclipse.JDT to eval this as a java expression.

EDIT:

In order to give a little bit more context about what I'm trying to achieve: It's related to a modification of Sharpen (converter of Java code to C#) in order to convert a bit mask string declaration in a valid C# int declaration (this bit mask notation is still not managed by C#).

Fab
  • 14,327
  • 5
  • 49
  • 68

2 Answers2

2

A simple solution would be to strip of the prefix "0b", replace any "_" with "", and then use Integer.parseInt(n, 2) to get the int value.

wero
  • 32,544
  • 3
  • 59
  • 84
1

I tried wero solution and my own solution and finally I kept mine because while not being too complex, it's faster. However, as I'm not that good in Java, maybe there is still room for improvement.

wero solution:

public static String simplerRewriteBitMask(String token) {
    String input = "0b1111_1111";
    input = input.replace("0b", "");
    input = input.replace("_", "");
    return Integer.toString(Integer.parseInt(input, 2));
}

my solution (with the improvements of JoopEggen)

private static String rewriteBitMask(String token) {
    int result = 0;
    for (int i = 2; i < token.length(); ++i) {
        char character = token.charAt(i);
        if (character != '_') {
            int bit = Character.digit(character, 2);
            result = result << 1;
            result |= bit;
        }
    }
    return Integer.toString(result);
}
Community
  • 1
  • 1
Fab
  • 14,327
  • 5
  • 49
  • 68
  • 1
    Upvoted because a solution without replace is a good idea, though improvements always possible. Newer java: `Integer.parseUnsignedInt` helps for "unsigned" values above Integer.MAX_VALUE. `<<` and `|` would be more fitting, as would be `charAt` and `Character.digit`. – Joop Eggen Feb 07 '16 at 11:53