在我的字节数组中,我具有一条消息的哈希值,该值由一些负值和正值组成。使用该(char)byte[i]语句可以轻松打印正值。
现在如何获得负值?
Answers:
这是一些可编译的代码:
byte[] byteArray = new byte[] { -1, -128, 1, 127 };
System.out.println(Arrays.toString(byteArray));
输出:
[-1, -128, 1, 127]
为什么要重新发明轮子...
byteArray.contentToString()
如果要将字节打印为字符,则可以使用String构造函数。
byte[] bytes = new byte[] { -1, -128, 1, 127 };
System.out.println(new String(bytes, 0));
试试看:
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 ]
试试这个: new String(byte[])