0

I've a char array

static char[] myArray  ={   
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x48, 0x48, 0x48, 0xb0, 0x00, 0xc0, 0x20,
0x20, 0x20, 0xc0, 0x00, 0xc0, 0x20, 0x20, 0x20, 0xc0, 0x00, 0x40, 0xa0, 0xa0, 0xa0, 0x20, 0x00,
0x00, 0x20, 0xf0, 0x20, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x08, 0xf8, 0x08,
};

How could I print it as 8-bit binary ?

Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134
  • Take a look at: http://stackoverflow.com/questions/917163/convert-a-string-like-testing123-to-binary-in-java – prashant Apr 23 '13 at 07:44
  • printing a single char: http://stackoverflow.com/questions/6381504/how-do-i-print-the-binary-representation-of-the-first-character-in-a-string Adding the loop is straightforward. – Vincent van der Weele Apr 23 '13 at 07:44
  • It's not as same as those links, the conversion to binary is the same, but the _8-bit_ part is not. – masoud Apr 23 '13 at 08:17

2 Answers2

3

Use toBinaryString for each item:

for (int i = 0; i < myArray.length; i++) {
        String b = Integer.toBinaryString(myArray[i]);

        if (b.length() < 8) {
            b = "000000000".substring(0, 8 - b.length()).concat(b);
        } else {
            b = b.substring(b.length() - 8);
        }

        System.out.print(b + " ");
 }

Output

00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 11111000 01001000 01001000 01001000 1011000 ...

masoud
  • 55,379
  • 16
  • 141
  • 208
0

if you output to be 0000000000000000f848484... then

    for(char c : myArray) {
        System.out.printf("%02x", (int)c);
    }
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275