简体   繁体   中英

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.

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

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.

You can directly convert String bindery to decimal representation using Integer#parseInt() method. No need to convert to Byte then to decimal

int decimalValue = Integer.parseInt(s[0], 2);

You should be using Byte b = Byte.valueof(s[i], 2) . Right now it parse the string treating it as decimal value. You should use valueOf and pass 2 as radix.

Skip the Byte step. Just parse it into an int with Integer.parseInt(String s, int radix) :

int result = Integer.parseInt(s[0], 2);

The 2 specifies base 2, whereas the code you're using treats the input strings as decimal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM