在Java Char数组中打印为二进制

时间:2013-04-23 07:41:32

标签: java binary system.out

我有一个char数组

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,
};

如何将其打印为8位二进制文​​件?

2 个答案:

答案 0 :(得分:3)

对每件商品使用toBinaryString

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 + " ");
 }

输出

  

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

答案 1 :(得分:0)

如果您输出为0000000000000000f848484...,那么

    for(char c : myArray) {
        System.out.printf("%02x", (int)c);
    }