How to convert a byte in binary representation into int in java

I have a String[] with byte values

String[] s = {"110","101","100","11","10","1","0"};

Looping through s, I want to get int values out of it.

I am currently using this

Byte b = new Byte(s[0]); // s[0] = 110
int result = b.intValue(); // b.intValue() is returning 110 instead of 6

From that, I am trying to get the results, {6, 5, 4, 3, 2, 1}

I am not sure of where to go from here. What can I do?

Thanks guys. Question answered.

Jon Skeet
people
quotationmark

You're using the Byte constructor which just takes a String and parses it as a decimal value. I think you actually want Byte.parseByte(String, int) which allows you to specify the radix:

for (String text : s) {
    byte value = Byte.parseByte(text, 2);
    // Use value
}

Note that I've used the primitive Byte value (as returned by Byte.parseByte) instead of the Byte wrapper (as returned by Byte.valueOf).

Of course, you could equally use Integer.parseInt or Short.parseShort instead of Byte.parseByte. Don't forget that bytes in Java are signed, so you've only got a range of [-128, 127]. In particular, you can't parse "10000000" with the code above. If you need a range of [0, 255] you might want to use short or int instead.

people

See more on this question at Stackoverflow