How to convert a byte array to a hex string in Java?
To convert a byte array to a hexadecimal string in Java, you can use the following method:
public static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
This method iterates over the bytes in the input array and converts each byte to a two-digit hexadecimal string using the String.format()
method. The resulting strings are then concatenated to create the final hexadecimal string.
Here's an example of how you can use this method:
byte[] bytes = {0x01, 0x02, 0x03, 0x04, 0x05};
String hex = bytesToHex(bytes); // hex is "0102030405"
Alternatively, you can use the DatatypeConverter
class from the javax.xml.bind
package to convert a byte array to a hexadecimal string:
byte[] bytes = {0x01, 0x02, 0x03, 0x04, 0x05};
String hex = DatatypeConverter.printHexBinary(bytes); // hex is "0102030405"