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:
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 & 0xff));
}
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 b & 0xff mask ensures that negative byte values (which are signed in Java) are correctly converted to their unsigned hexadecimal representation. 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"Note: String.format is convenient but can be slow in tight loops. For performance-critical code, consider a precomputed hex lookup table or the HexFormat approach below.
Alternatively, for Java 16 and newer, you can use the modern java.util.HexFormat class, which replaces the deprecated DatatypeConverter:
import java.util.HexFormat;
byte[] bytes = {0x01, 0x02, 0x03, 0x04, 0x05};
String hex = HexFormat.of().formatHex(bytes); // hex is "0102030405"