How to convert Hex to ASCII in Java
Published: January 20, 2010 , Updated: January 20, 2010 , Author: mkyong
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
Any Java questions or problems? please post at this JavaNullPointer.com forum, see you there ~
superb code, thanks.
Works fine even with extended ASCII (èéòà..). It saves me 15 minutes to write it on my own
Thank you for Hex to String function. It save my day!
Don’t re-invent the wheel, just use String.format.
Hi,
i go through the API again, String.format is use to format the String only, may i know how do convert String to Hex and vise verse? Can you provide a short example? Thanks~