Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 377
smashsenpai Avatar asked Dec 29 '25 17:12

smashsenpai


2 Answers

You can use the overloaded Integer.parseInt(String s, int radix) method for such a conversion. This way you can just skip the Byte b = new Byte(s[0]); piece of code.

int result = Integer.parseInt(s[0], 2); // radix 2 for binary
like image 88
Rahul Avatar answered Dec 31 '25 07:12

Rahul


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.

like image 20
Jon Skeet Avatar answered Dec 31 '25 07:12

Jon Skeet