I came across the following solution for the print method, which seems to work and gives the corect output:
public static void print(byte[] bytes) {
        String line ="";
        for (byte b1 : bytes){
            String s1 = String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(' ', '0');
            line += s1 + " ";
        }
        System.out.println( line.trim() );
    }
But I don't undestand how the following works:
String s1 = String.format("%8s", Integer.toBinaryString(b1 & 0xFF)).replace(' ', '0');
What does "b1 & 0xFF" does and why replace ' ' with 0?