Convert Hex to ASCII in Java

1. Overview

In this quick article, we’re going to do some simple conversions between the Hex and ASCII formats.

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

Now, let’s look at our options to convert ASCII values to Hex:

  1. Convert String to char array
  2. Cast each char to an int
  3. 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

Similarly, let’s do a Hex to ASCII format conversion in three steps :

  1. Cut the Hex value in 2 char groups
  2. Convert it to base 16 Integer using Integer.parseInt(hex, 16) and cast to char
  3. 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

Finally, using these methods, let’s do a quick test :

@Test
public static void whenHexToAscii() {
    String asciiString = "www.maixuanviet.com";
    String hexEquivalent = 
      "7777772e6261656c64756e672e636f6d";

    assertEquals(asciiString, hexToAscii(hexEquivalent));
}

@Test
public static void whenAsciiToHex() {
    String asciiString = "www.maixuanviet.com";
    String hexEquivalent = 
      "7777772e6261656c64756e672e636f6d";

    assertEquals(hexEquivalent, asciiToHex(asciiString));
}

5. Conclusion

To conclude, we looked at the simplest ways of converting between ASCII and Hex using Java.

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.

Related posts:

Java Program to Implement RoleUnresolvedList API
Java Program to Check if an UnDirected Graph is a Tree or Not Using DFS
A Guide to ConcurrentMap
Java Program to Implement Radix Sort
Java 8 Predicate Chain
Introduction to Spring Cloud CLI
Java Program to Find the Number of Ways to Write a Number as the Sum of Numbers Smaller than Itself
Hướng dẫn Java Design Pattern – Mediator
Java Program to Check if a Directed Graph is a Tree or Not Using DFS
Java Program to Implement Rolling Hash
Hướng dẫn Java Design Pattern – Singleton
Java Program to Implement Graph Structured Stack
Java Program to Check whether Graph is a Bipartite using 2 Color Algorithm
Spring Boot - Thymeleaf
REST Web service: Tạo ứng dụng Java RESTful Client với Jersey Client 2.x
Implementing a Binary Tree in Java
Introduction to Spring Boot CLI
Java Program to Implement Binary Search Tree
Introduction to Spring Cloud Stream
Java Program to Implement Uniform-Cost Search
Extract links from an HTML page
Java Concurrency Interview Questions and Answers
Hướng dẫn sử dụng luồng vào ra nhị phân trong Java
OAuth2 for a Spring REST API – Handle the Refresh Token in Angular
Injecting Prototype Beans into a Singleton Instance in Spring
Đồng bộ hóa các luồng trong Java
Send an email using the SMTP protocol
Java Program to Implement Selection Sort
Java Program to Check Multiplicability of Two Matrices
Xây dựng ứng dụng Client-Server với Socket trong Java
Java Program to Represent Graph Using Adjacency List
Multi Dimensional ArrayList in Java