How to convert a byte to its binary string representation
Solution 1
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();
}
Related videos on Youtube
Comments
-
Sean over 3 years
For example, the bits in a byte
B
are10000010
, how can I assign the bits to the stringstr
literally, that is,str = "10000010"
.Edit
I read the byte from a binary file, and stored in the byte array
B
. I useSystem.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 ignore0
, for example, assumeB[0]
has 00000001, the output is1
instead of00000001
-
Dave Newton almost 12 yearsI'm confused; is this a trick?
-
SLaks almost 12 yearsAre you asking how to convert a
byte
to a string in base 2? -
chaotic3quilibrium over 5 yearsI 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
, andLong
. stackoverflow.com/a/54950845/501113 -
NomadMaker almost 4 yearsString#Format() might be able to handle this, if you told it to use a width of 8. Likewise System.out.printf().
-
-
Sean almost 12 yearsI tried this method. In my case, I read the byte from a binary file, and stored in the byte array
B
. I useSystem.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 convertsB[i]
to a negative int value. (b) if the bits begins with 0, the output ignore0
, for example, assumeB[0]
has00000001
, the output is1
instead of00000001
-
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 is127
; b) You can easily fix that by using thisString.format("%8s", Integer.toBinaryString(b)).replace(' ', '0')
to left pad the resulting string with zeros. -
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 almost 12 years@Sean: Yes, just
&
it with0xFF
. -
João Silva almost 12 years@Sean:
& 0xFF
basically converts asigned byte
to anunsigned integer
. For example,-129
, like you said, is represented by11111111111111111111111110000001
. In this case, you basically want the first (least significant) 8 bits, so you AND (&
) it with0xFF
(00000000000000000000000011111111
), effectively cleaning the 1's to the left that we don't care about, leaving out just10000001
. -
João Silva almost 12 years@Sean: Ah yes, you need to
replace
the result, after theString.format
, like in the example above. Basically,String.format
left pads the string with spaces up to 8%8s
, and thenreplace
takes care of replacing those spaces with0
s. -
Mirco Widmer over 10 yearsI think this example could be improved, because
byte b1 = (byte) 129;
overflows. -
DavidPostill over 9 yearsCould 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 over 7 yearshey! 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 about 5 yearsWhat exactly does the + 0x100 do? You're adding 256 to the resulting integer, but why?
-
Raekye about 5 years@ConnerDassen It ensures that the binary string is 0 padded. For example, if
b
is1
, without+ 0x100
you will just get"1"
as your string. By adding1
, you get100000001
, 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 useInteger.toBinaryString(b & 0xff)
. The& 0xff
fixes the negative/two's complement issues -
gmk57 over 3 yearsI needed a little-endian solution, and this one was easiest to adapt (by changing the iteration order to 0 -> 7). Thanks!