Convert a string representation of a hex dump to a byte array using Java?
To convert a string representation of a hex dump to a byte array in Java, you can use the DatatypeConverter class's parseHexBinary method.
To convert a string representation of a hex dump to a byte array in Java, you can use java.util.HexFormat (available in Java 17+). This modern standard library method replaces the obsolete JAXB DatatypeConverter class.
Here is a complete, runnable example:
import java.util.Arrays;
import java.util.HexFormat;
public class HexConverter {
public static void main(String[] args) {
String hexString = "01a1f6";
byte[] bytes = HexFormat.of().parseHex(hexString);
System.out.println(Arrays.toString(bytes));
}
}This will give you a byte array containing the bytes represented by the hex string.
Alternatively, for older Java versions, you can use a loop to parse the hex string and manually convert it to a byte array. This example also includes validation to reject invalid hex characters:
import java.util.Arrays;
public class HexConverter {
public static void main(String[] args) {
String hexString = "01a1f6";
byte[] bytes = new byte[hexString.length() / 2];
for (int i = 0; i < hexString.length(); i += 2) {
int d1 = Character.digit(hexString.charAt(i), 16);
int d2 = Character.digit(hexString.charAt(i + 1), 16);
if (d1 == -1 || d2 == -1) {
throw new IllegalArgumentException("Invalid hex character at index " + i);
}
bytes[i / 2] = (byte) ((d1 << 4) + d2);
}
System.out.println(Arrays.toString(bytes));
}
}I hope this helps! Let me know if you have any questions.