Here’s a Java example to show how to convert Hex to ASCII or vice verse in Java. The conversion process is depend on this formula “Hex<==>Decimal<==>ASCII“.

  • ASCII to Hex – Convert String to char array, cast it to integer(decimal) follow by Integer.toHexString to convert it to Hex value.
  • Hex to ASCII – Cut the Hex value in pairs format, convert it to radix 16 interger(decimal) Integer.parseInt(hex, 16), and cast it back to char.

Example

public class StringToHex{
 
  public String convertStringToHex(String str){
 
	  char[] chars = str.toCharArray();
 
	  StringBuffer hex = new StringBuffer();
	  for(int i = 0; i < chars.length; i++){
	    hex.append(Integer.toHexString((int)chars[i]));
	  }
 
	  return hex.toString();
  }
 
  public String convertHexToString(String hex){
 
	  StringBuilder sb = new StringBuilder();
	  StringBuilder temp = new StringBuilder();
 
	  //49204c6f7665204a617661 split into two characters 49, 20, 4c...
	  for( int i=0; i<hex.length()-1; i+=2 ){
 
	      //grab the hex in pairs
	      String output = hex.substring(i, (i + 2));
	      //convert hex to decimal
	      int decimal = Integer.parseInt(output, 16);
	      //convert the decimal to character
	      sb.append((char)decimal);
 
	      temp.append(decimal);
	  }
	  System.out.println("Decimal : " + temp.toString());
 
	  return sb.toString();
  }
 
  public static void main(String[] args) {
 
	  StringToHex strToHex = new StringToHex();
	  System.out.println("\n***** Convert ASCII to Hex *****");
	  String str = "I Love Java!";  
	  System.out.println("Original input : " + str);
 
	  String hex = strToHex.convertStringToHex(str);
 
	  System.out.println("Hex : " + hex);
 
	  System.out.println("\n***** Convert Hex to ASCII *****");
	  System.out.println("Hex : " + hex);
	  System.out.println("ASCII : " + strToHex.convertHexToString(hex));
  }
}

Output

***** Convert ASCII to Hex *****
Original input : I Love Java!
Hex : 49204c6f7665204a61766121
 
***** Convert Hex to ASCII *****
Hex : 49204c6f7665204a61766121
Decimal : 7332761111181013274971189733
ASCII : I Love Java!

Reference

1. http://en.wikipedia.org/wiki/Hexadecimal
2. http://mindprod.com/jgloss/hex.html

Tags :
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

Related Posts

Popular Posts