有没有更简单的方法将字节数组转换为2字节大小的十六进制字符串?

Tom*_*ito 1 java hex bytearray

有没有更简单的方法来实现这个?或JDK或其他lib中实现的方法?

/**
 * 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}));
}
Run Code Online (Sandbox Code Playgroud)

输出为:"08 0A 0C"(不含空格)

Bal*_*usC 7

至少使用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();
}
Run Code Online (Sandbox Code Playgroud)


Jas*_*ols 6

Apache Commons-Codec具有Hex类,可以满足您的需求:

String hexString = Hex.encodeHexString(bytes);
Run Code Online (Sandbox Code Playgroud)

到目前为止最简单的方法.不要乱用二元运算符,使用库来做脏工作=)