Convert Hex to String in Java

The Hex or Hexadecimal strings are made of a hexadecimal numbering system that uses the Base of 16 system. The hex is used to represent the long binary values.
In Java, we can convert a normal string to a hex string using the method toHexString()
, but to convert a hex string to a normal one, we need to convert each string character from hex to char. This tutorial demonstrates how to convert a hex string to a text string in Java.
Convert Hex to String in Java
Converting the hexadecimal
to string is a step-by-step process in Java.
- Get the hexadecimal value of the string.
- Use the method
toCharArray
to convert the string into a character array. - Read every two characters from the array and convert them to the string.
- Now, Parse the strings obtained above into base 16 integers and then cast them into char.
- Finally, add all the characters to one string by concatenating them.
Source Code:
package delftstack;
import java.util.Scanner;
public class Hex_String {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter a Hexadecimal value you want to convert: ");
String HexString = sc.next();
String OutputString = new String();
char[] Temp_Char = HexString.toCharArray();
for(int x = 0; x < Temp_Char.length; x=x+2) {
String Temp_String = ""+Temp_Char[x]+""+Temp_Char[x+1];
char character = (char)Integer.parseInt(Temp_String, 16);
OutputString = OutputString + character;
}
System.out.println("The String of the hexadecimal value is: ");
System.out.println(OutputString);
}
}
The code above will ask for a hexadecimal value and then convert it.
Output:
Please Enter a Hexadecimal value you want to convert:
48656c6c6f2120546869732069732064656c6674737461636b2e636f6d
The String of the hexadecimal value is:
Hello! This is delftstack.com
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn Facebook