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