Home » Core Java » Convert Hex to/from ASCII in Java

About Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).

Convert Hex to/from ASCII in Java

Hello. In this tutorial, we will explore HEX to/from ASCII conversion in Java.

1. Introduction

In order to convert ASCII to hexadecimal values in Java is done in the following steps –

  • Covert the string to the character array
  • Convert each string to an integer
  • Convert each integer value to toHexString()

Hex to ASCII conversion in Java is done in the following steps –

  • Cut the hex value into two-character groups
  • Convert it to Base16 integer using Integer.valueOf(…) method and cast to char
  • Append all characters in StringBuilder

2. Practice

Let us dive into some practice stuff from here and I am assuming that you already have the Java 1.8 or greater installed on your local machine. I am using JetBrains IntelliJ IDEA as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Understanding the ASCII to Hex conversion

Create an implementation class in the com.practice package and add the following code. The code will convert the ASCII value to a hex string and print the result on the IDE console.

AsciiToHex.java

package com.practice;

import java.util.Arrays;
import java.util.List;

public class AsciiToHex {

  private static String convertToHex(String asciiString) throws Exception {
    // convert string to char array
    char[] chrs = asciiString.toCharArray();

    StringBuilder builder = new StringBuilder();
    // iterate over each element and convert it to integer
    for (char item: chrs) {
      int i = (int) item;
      // convert int value to hex string
      builder.append(Integer.toHexString(i).toUpperCase());
    }

    return builder.toString();
  }

  public static void main(String[] args) {
    List<String> asciis = Arrays.asList(
        "good morning world", 
        "welcome to javacodegeeks", 
        "Convert ASCII to Hex in Java");
    try {
      for (String s: asciis) {
        if (!s.isEmpty()) {
          System.out.println("Original string= " + s);
          System.out.println("Hex Converted string= " + convertToHex(s) + "\n");
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Run the file as a java application and it will be shown the logs in the IDE console.

Console logs

Original string= good morning world
Hex Converted string= 676F6F64206D6F726E696E6720776F726C64

Original string= welcome to javacodegeeks
Hex Converted string= 77656C636F6D6520746F206A617661636F64656765656B73

Original string= Convert ASCII to Hex in Java
Hex Converted string= 436F6E7665727420415343494920746F2048657820696E204A617661

2.2 Understanding the Hex to ASCII conversion

Create an implementation class in the com.practice package and add the following code. The code will convert the hex string into the ASCII value and print the result on the IDE console.

HexToAscii.java

package com.practice;

import java.util.Arrays;
import java.util.List;

public class HexToAscii {

  private static String convertToAscii(String hexString) throws Exception {
    if (hexString.length() %2 !=0) {
      System.err.println("Input hex string is invlaid");
      throw new Exception("Input input");
    }

    StringBuilder builder = new StringBuilder();
    for (int i=0 ; i<hexString.length(); i=i+2) {
      // splitting strings into two character group
      String str = hexString.substring(i, i+2);
      // converting each character group using valueOf(...) method
      int n = Integer.valueOf(str, 16);
      // casting to char and appending to builder
      builder.append((char)n);
    }

    return builder.toString();
  }

  public static void main(String[] args) {
    List<String> hexStrings = Arrays.asList(
        "676f6f64206d6f726e696e6720776f726c64", 
        "77656c636f6d6520746f206a617661636f64656765656b73", 
        "436f6e766572742048657820746f20415343494920696e204a61766120");
    try {
      for (String s: hexStrings) {
        if (!s.isEmpty()) {
          System.out.println("Original string= " + s);
          System.out.println("Ascii Converted string= " + convertToAscii(s) + "\n");
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Run the file as a java application and it will be shown the logs in the IDE console.

Console logs

Original string= 676f6f64206d6f726e696e6720776f726c64
Ascii Converted string= good morning world

Original string= 77656c636f6d6520746f206a617661636f64656765656b73
Ascii Converted string= welcome to javacodegeeks

Original string= 436f6e766572742048657820746f20415343494920696e204a61766120
Ascii Converted string= Convert Hex to ASCII in Java

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

3. Download the Project

Download
You can download the full source code of this example here: Convert Hex to/from ASCII in Java

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments