Java byte to String
Today we have a quick tip for you guys, how to convert byte
variable to the String
object. You might say this is easy, just use the Integer.toBinaryString()
method but this solution comes with a major problem – as a output you get a String
of a different length.
The problem
for (int b=0; b <= Byte.MAX_VALUE; b++) { System.out.println(b + "\t->\t" + Integer.toBinaryString((byte)b)); }
Results in:
0 -> 0 1 -> 1 2 -> 10 3 -> 11 4 -> 100 5 -> 101 6 -> 110 7 -> 111 8 -> 1000 9 -> 1001 10 -> 1010 … // up to 126 -> 1111110 127 -> 1111111
How to get a String
representation of a byte
that might be used to display in a table etc.?
The solution
public class JavaByteToString { public static String byteToString(byte b) { return String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0'); } public static void main(String[] args) { for (int b=0; b <= Byte.MAX_VALUE; b++) { System.out.println(b + "\t->\t" + byteToString((byte)b)); } } }
This code will give you the output you are are here for :)
0 -> 00000000 1 -> 00000001 2 -> 00000010 3 -> 00000011 4 -> 00000100 5 -> 00000101 6 -> 00000110 7 -> 00000111 8 -> 00001000 9 -> 00001001 10 -> 00001010 … // up to 126 -> 01111110 127 -> 01111111
Download this sample code here.
What come to my mind if such output comes
is that leading 0′s are missing. So simplest method would be append zero in front of that.
How many zero’s we need to append that can be configured. I think the best way is to create a new method that will handles this case.
Just append the 0′s
This method is also nice, but I think this would not come in mind at first.
So this mode code look like