示例 1:将字节数组转换为十六进制值
public class ByteHex {
public static void main(String[] args) {
byte[] bytes = {10, 2, 15, 11};
for (byte b : bytes) {
String st = String.format("%02X", b);
System.out.print(st);
}
}
}
输出
0A020F0B
在上面的程序中,我们有一个名为 bytes 的字节数组。要将字节数组转换为十六进制值,我们会循环遍历数组中的每个字节,并使用 String
的 format() 方法。
我们使用 %02X
来打印两位 (02
) 的十六进制 (X
) 值,并将其存储在字符串 st 中。
对于大型字节数组转换,这是一个相对较慢的过程。我们可以使用下面显示的字节操作来显著提高执行速度。
示例 2:使用字节操作将字节数组转换为十六进制值
public class ByteHex {
private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static void main(String[] args) {
byte[] bytes = {10, 2, 15, 11};
String s = bytesToHex(bytes);
System.out.println(s);
}
}
程序的输出与示例 1相同。