Is there a simpler way to convert a byte array to a 2-byte-size hexadecimal string?
- by Tom Brito
Is there a simpler way of implement this? Or a implemented method in JDK or other 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}));
}
the output is: "08 0A 0C" (without the spaces)