0

I have a byte array that I would like to print in binary.I could loop through the array and concatenate Integer.toString(byteArray[i], 2) or Integer.toBinaryString to a string, but any bytes that start with a 0 will have that 0 trimmed off. How can I avoid this?

For example, if the array were:

{0b11110000, 0b10101010, 0b11001100, 0b00001111}

I would get:

1111000010101010110011001111     // what is printed
11110000101010101100110000001111 // what I want
// 0's are missing      ^--^
Camander
  • 147
  • 1
  • 10
  • 1
    possible duplicate of [How to get 0-padded binary representation of an integer in java?](http://stackoverflow.com/questions/4421400/how-to-get-0-padded-binary-representation-of-an-integer-in-java) – Kevin Workman Feb 25 '15 at 15:58
  • 1
    possible duplicate of [How can I pad an integers with zeros on the left?](http://stackoverflow.com/questions/473282/how-can-i-pad-an-integers-with-zeros-on-the-left) –  Feb 25 '15 at 16:03

1 Answers1

1

Use String format like on this example:

byte b2 = (byte) 2;
String s2 = String.format("%8s", Integer.toBinaryString(b2 & 0xFF)).replace(' ', '0');
System.out.println(s2); // 00000010
Vítor Martins
  • 1,430
  • 4
  • 20
  • 41