Is there an easy way to print byte[] array ( zeros and ones, basically to every bit convert in ascii '1' or ascii '0') to the console ?
4 Answers
You can output the individual bytes by converting their numeric value to base 2. Here are two ways to do it. In both, I will use this byte array:
byte[] array = "HälLø123§$%".getBytes();
Walk the array
for(final byte b : array){
System.out.print(Integer.toString(b & 0xFF /* thx Jason Day */, 2));
}
Output:
10010001100001110100100110110010011001100001110111000110001011001001100110110000101010011110010001001010
Reference:
Use BigInteger
If you want to output the entire array in one piece, use BigInteger:
System.out.println(new BigInteger(array).toString(2));
Output:
100100011000011101001000110110001001100110000111011100000110001001100100011001111000010101001110010010000100101
Reference:
2 Comments
If you want to print the binary representation of each element, you can do something like this:
StringBuilder sb = new StringBuilder();
sb.append("[");
String comma = "";
for (byte b : array) {
int i = b & 0xFF; // cast to int and mask the sign bit
sb.append(comma);
comma = ",";
sb.append(Integer.toBinaryString(i));
}
sb.append("]");
System.out.println(sb.toString());
Comments
You can use commons-codec BinaryCodec:
BinaryCodec.toAsciiString(array)
For better control on the output, you can use toAsciiChars(..) and print the char[].
(If you simply want to output the array values - java.util.Arrays.toString(array));
4 Comments
Note: This outputs individual bytes, not individual bits. But as it may still be useful for someone, I'll let it here.
Here the solution for my understanding of the question:
byte[] data = {0, 1, 0, 1, 1, 0};
StringBuilder sb = new StringBuilder(data.length);
for(byte b : data) {
sb.append(b);
}
System.out.println(sb);
This should output 010110.
Integer.toBinaryString()for bytes. Baffles me why there's no such method in theByteclass, to be honest.