Search code examples
javabinarybyte

Java | Binary string to byte


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.


Solution

    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.