java-convert-hex-to-ascii
Convert Hex to ASCII in Java
1. Overview
In a typical use case, the Hex format can be used to write down very large integer values in a compact form. For example, AD45 is shorter than its decimal equivalent 44357 and as values increase the difference in length becomes even more pronounced.
2. ASCII to Hex
-
Convert String to char array
-
Cast each char to an int
-
Use Integer.toHexString() to convert it to Hex
Here’s a quick example how we can achieve above steps:
private static String asciiToHex(String asciiStr) {
char[] chars = asciiStr.toCharArray();
StringBuilder hex = new StringBuilder();
for (char ch : chars) {
hex.append(Integer.toHexString((int) ch));
}
return hex.toString();
}
3. Hex to ASCII format
-
Cut the Hex value in 2 char groups
-
Convert it to base 16 Integer using Integer.parseInt(hex, 16) and cast to char
-
Append all chars in a StringBuilder
Let’s look at an example how we can achieve above steps:
private static String hexToAscii(String hexStr) {
StringBuilder output = new StringBuilder("");
for (int i = 0; i < hexStr.length(); i += 2) {
String str = hexStr.substring(i, i + 2);
output.append((char) Integer.parseInt(str, 16));
}
return output.toString();
}
4. Test
@Test
public static void whenHexToAscii() {
String asciiString = "www.baeldung.com";
String hexEquivalent =
"7777772e6261656c64756e672e636f6d";
assertEquals(asciiString, hexToAscii(hexEquivalent));
}
@Test
public static void whenAsciiToHex() {
String asciiString = "www.baeldung.com";
String hexEquivalent =
"7777772e6261656c64756e672e636f6d";
assertEquals(hexEquivalent, asciiToHex(asciiString));
}
5. Conclusion
The implementation of all these examples and code snippets can be found in the github project – simply import the project and run as it is.