如何将字节数组中的数据打印为字符?


Answers:


22

好吧,如果您乐于以十进制格式打印它,则可以通过屏蔽使其变为正数:

int positive = bytes[i] & 0xff;

但是,如果要打印散列,则使用十六进制会更常规。关于堆栈溢出,还有很多其他问题要解决,即在Java中将二进制数据转换为十六进制字符串。


242

怎么Arrays.toString(byteArray)

这是一些可编译的代码:

byte[] byteArray = new byte[] { -1, -128, 1, 127 };
System.out.println(Arrays.toString(byteArray));

输出:

[-1, -128, 1, 127]

为什么要重新发明轮子...


4
在科特林,这是byteArray.contentToString()
Vlad

23

如果要将字节打印为字符,则可以使用String构造函数。

byte[] bytes = new byte[] { -1, -128, 1, 127 };
System.out.println(new String(bytes, 0));

13
不建议使用构造函数String(byte [],int)。改用String(byte [],Charset),例如,新的String(bytes,Charset.forName(“ ISO-8859-1”))。
克拉斯·林德贝克(KlasLindbäck)

15

试试看:

public static String print(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    sb.append("[ ");
    for (byte b : bytes) {
        sb.append(String.format("0x%02X ", b));
    }
    sb.append("]");
    return sb.toString();
}

例:

 public static void main(String []args){
    byte[] bytes = new byte[] { 
        (byte) 0x01, (byte) 0xFF, (byte) 0x2E, (byte) 0x6E, (byte) 0x30
    };

    System.out.println("bytes = " + print(bytes));
 }

输出: bytes = [ 0x01 0xFF 0x2E 0x6E 0x30 ]


1
如果要将字符打印为十六进制,这是更好的选择之一。
Per Lundberg '18

看起来像将它们打印为数字
毫米


8
byte[] buff = {1, -2, 5, 66};
for(byte c : buff) {
    System.out.format("%d ", c);
}
System.out.println();

让你

1 -2 5 66 
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.