How to convert a byte to its binary string representation

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.


I used this. Similar idea to other answers, but didn't see the exact approach anywhere :)

System.out.println(Integer.toBinaryString((b & 0xFF) + 0x100).substring(1));

0xFF is 255, or 11111111 (max value for an unsigned byte). 0x100 is 256, or 100000000

The & upcasts the byte to an integer. At that point, it can be anything from 0-255 (00000000 to 11111111, I excluded the leading 24 bits). + 0x100 and .substring(1) ensure there will be leading zeroes.

I timed it compared to João Silva's answer, and this is over 10 times faster. http://ideone.com/22DDK1 I didn't include Pshemo's answer as it doesn't pad properly.


Is this what you are looking for?

converting from String to byte

byte b = (byte)(int)Integer.valueOf("10000010", 2);
System.out.println(b);// output -> -126

converting from byte to String

System.out.println(Integer.toBinaryString((b+256)%256));// output -> "10000010"

Or as João Silva said in his comment to add leading 0 we can format string to length 8 and replace resulting leading spaces with zero, so in case of string like " 1010" we will get "00001010"

System.out.println(String.format("%8s", Integer.toBinaryString((b + 256) % 256))
                         .replace(' ', '0'));

You could check each bit on the byte then append either 0 or 1 to a string. Here is a little helper method I wrote for testing:

public static String byteToString(byte b) {
    byte[] masks = { -128, 64, 32, 16, 8, 4, 2, 1 };
    StringBuilder builder = new StringBuilder();
    for (byte m : masks) {
        if ((b & m) == m) {
            builder.append('1');
        } else {
            builder.append('0');
        }
    }
    return builder.toString();
}

Get each bit of byte and convert to string. Say byte has 8 bits, and we can get them one by one via bit move. For example, we move the second bit of the byte 6 bits to right, the second bit at last of bit of 8 bits, then and(&) with 0x0001 to clean the front bits.

public static String getByteBinaryString(byte b) {
    StringBuilder sb = new StringBuilder();
    for (int i = 7; i >= 0; --i) {
        sb.append(b >>> i & 1);
    }
    return sb.toString();
}