1

I want to convert a string that consists of 8 binary numbers to a byte. I have tried this method:

byte b = Byte.parseByte(s, 2);

Which works fine if the string is "00000000", but doesn't work if it is "11111111".

I suspect is has something to do with the Radix but I can not figure it out.

1 Answer 1

1
  1. Use Integer.parseInt with a radix of 2 like this Integer.parseInt("11111111", 2)
  2. Then if you really want it as a byte simply cast the integer to a byte like this (byte) intValue

So the complete code is:

System.out.println((byte) Integer.parseInt("11111111", 2));

Output:

-1

NB: Why -1? because byte is a signed integer of 8 bits going from -128 to 127 so here instead of having 255 you get -1.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.