有没有更简单的实现方法?还是 JDK 或其他库中的实现方法?
/**
* Convert a byte array to 2-byte-size hexadecimal String.
*/
public static String to2DigitsHex(byte[] bytes) {
String hexData = "";
for (int i = 0; i < bytes.length; i++) {
int intV = bytes[i] & 0xFF; // positive int
String hexV = Integer.toHexString(intV);
if (hexV.length() < 2) {
hexV = "0" + hexV;
}
hexData += hexV;
}
return hexData;
}
public static void main(String[] args) {
System.out.println(to2DigitsHex(new byte[] {8, 10, 12}));
}
输出是:“08 0A 0C”(没有空格)
最佳答案
至少使用 StringBuilder#append()
代替 stringA += stringB
以提高性能并节省内存。
public static String binaryToHexString(byte[] bytes) {
StringBuilder hex = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
int i = (b & 0xFF);
if (i < 0x10) hex.append('0');
hex.append(Integer.toHexString(i));
}
return hex.toString();
}
关于java - 有没有更简单的方法将字节数组转换为 2 字节大小的十六进制字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2645974/