How to convert a byte to its binary string representation

234,820

Solution 1

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.

Solution 2

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.

Solution 3

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'));

Solution 4

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();
}

Solution 5

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();
}
Share:
234,820

Related videos on Youtube

Sean
Author by

Sean

Hello World!! Hello friends!!

Updated on November 04, 2020

Comments

  • Sean
    Sean over 3 years

    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

    • Dave Newton
      Dave Newton almost 12 years
      I'm confused; is this a trick?
    • SLaks
      SLaks almost 12 years
      Are you asking how to convert a byte to a string in base 2?
    • chaotic3quilibrium
      chaotic3quilibrium over 5 years
      I just added an answer to another thread for doing this (converting a value to a String of binary digits) which works for Boolean, Byte, Short, Char, Int, and Long. stackoverflow.com/a/54950845/501113
    • NomadMaker
      NomadMaker almost 4 years
      String#Format() might be able to handle this, if you told it to use a width of 8. Likewise System.out.printf().
  • Sean
    Sean almost 12 years
    I tried this method. In my case, I read the byte from a binary file, and stored in the byte array B. I use System.out.println(Integer.toBinaryString(B[i])). When I use this methods, the problem is (a) when the bits begins with (leftmost) 1, the output is not correct because it converts B[i] to a negative int value. (b) if the bits begins with 0, the output ignore 0, for example, assume B[0] has 00000001, the output is 1 instead of 00000001
  • João Silva
    João Silva almost 12 years
    @Sean: a) happens because a byte in Java is an 8-bit signed two's complement integer. Its minimum value is -128 (2^8), and its maximum value is 127; b) You can easily fix that by using this String.format("%8s", Integer.toBinaryString(b)).replace(' ', '0') to left pad the resulting string with zeros.
  • Sean
    Sean almost 12 years
    @ João: thanks for your advice. Do you have any idea about how to address (a), how to store the original bit format (begins with 1) into the string?
  • João Silva
    João Silva almost 12 years
    @Sean: Yes, just & it with 0xFF.
  • João Silva
    João Silva almost 12 years
    @Sean: & 0xFF basically converts a signed byte to an unsigned integer. For example, -129, like you said, is represented by 11111111111111111111111110000001. In this case, you basically want the first (least significant) 8 bits, so you AND (&) it with 0xFF (00000000000000000000000011111111), effectively cleaning the 1's to the left that we don't care about, leaving out just 10000001.
  • João Silva
    João Silva almost 12 years
    @Sean: Ah yes, you need to replace the result, after the String.format, like in the example above. Basically, String.format left pads the string with spaces up to 8 %8s, and then replace takes care of replacing those spaces with 0s.
  • Mirco Widmer
    Mirco Widmer over 10 years
    I think this example could be improved, because byte b1 = (byte) 129; overflows.
  • DavidPostill
    DavidPostill over 9 years
    Could you please edit your answer to give an explanation of why this code answers the question? Code-only answers are discouraged, because they don't teach the solution.
  • Sid
    Sid over 7 years
    hey! got a question about this. I have a Base64 representation string of a PDF, I need to convert into Binary. Basically, Base64->byte->binary.Will this code work?
  • Conner Dassen
    Conner Dassen about 5 years
    What exactly does the + 0x100 do? You're adding 256 to the resulting integer, but why?
  • Raekye
    Raekye about 5 years
    @ConnerDassen It ensures that the binary string is 0 padded. For example, if b is 1, without + 0x100 you will just get "1" as your string. By adding 1, you get 100000001, and if you take the substring ignoring the first character you will get the proper "00000001". If you do not want your string to be padded you can simply use Integer.toBinaryString(b & 0xff). The & 0xff fixes the negative/two's complement issues
  • gmk57
    gmk57 over 3 years
    I needed a little-endian solution, and this one was easiest to adapt (by changing the iteration order to 0 -> 7). Thanks!