javabinarybyte

How to convert a byte to its binary string representation


For example, the bits in a byte B are 10000010, how can I assign the bits to the string str literally, that is, str = "10000010".

Edit

I read the byte from a binary file, and stored in the byte array B. I use System.out.println(Integer.toBinaryString(B[i])). the problem is

(a) when the bits begin with (leftmost) 1, the output is not correct because it converts B[i] to a negative int value.

(b) if the bits begin with 0, the output ignore 0, for example, assume B[0] has 00000001, the output is 1 instead of 00000001


Solution

  • Use Integer#toBinaryString():

    byte b1 = (byte) 129;
    String s1 = String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(' ', '0');
    System.out.println(s1); // 10000001
    
    byte b2 = (byte) 2;
    String s2 = String.format("%8s", Integer.toBinaryString(b2 & 0xFF)).replace(' ', '0');
    System.out.println(s2); // 00000010
    

    DEMO.