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

在字节数组中,我有一个消息的 大麻值,它由一些负值和正值组成。使用 (char)byte[i]语句可以轻松地打印正值。

现在我怎样才能得到负值呢?

260398 次浏览

Well if you're happy printing it in decimal, you could just make it positive by masking:

int positive = bytes[i] & 0xff;

If you're printing out a hash though, it would be more conventional to use hex. There are plenty of other questions on Stack Overflow addressing converting binary data to a hex string in Java.

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

gets you

1 -2 5 66

How about Arrays.toString(byteArray)?

Here's some compilable code:

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

Output:

[-1, -128, 1, 127]

Why re-invent the wheel...

If you want to print the bytes as chars you can use the String constructor.

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

Try this one : new String(byte[])

Try it:

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();
}

Example:

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

Output: bytes = [ 0x01 0xFF 0x2E 0x6E 0x30 ]

in Kotlin you can use :

println(byteArray.contentToString())