001package ca.bc.webarts.widgets; 002 003public class StringToHex{ 004 005 public String convertStringToHex(String str){ 006 007 char[] chars = str.toCharArray(); 008 009 StringBuffer hex = new StringBuffer(); 010 for(int i = 0; i < chars.length; i++){ 011 hex.append(Integer.toHexString((int)chars[i])); 012 } 013 014 return hex.toString(); 015 } 016 017 public String convertHexToString(String hex){ 018 019 StringBuilder sb = new StringBuilder(); 020 StringBuilder temp = new StringBuilder(); 021 022 //49204c6f7665204a617661 split into two characters 49, 20, 4c... 023 for( int i=0; i<hex.length()-1; i+=2 ){ 024 025 //grab the hex in pairs 026 String output = hex.substring(i, (i + 2)); 027 //convert hex to decimal 028 int decimal = Integer.parseInt(output, 16); 029 //convert the decimal to character 030 sb.append((char)decimal); 031 032 temp.append(decimal); 033 } 034 System.out.println("Decimal : " + temp.toString()); 035 036 return sb.toString(); 037 } 038 039 public static void main(String[] args) { 040 041 StringToHex strToHex = new StringToHex(); 042 System.out.println("\n***** Convert ASCII to Hex *****"); 043 String str = "I Love Java!"; 044 System.out.println("Original input : " + str); 045 046 String hex = strToHex.convertStringToHex(str); 047 048 System.out.println("Hex : " + hex); 049 050 System.out.println("\n***** Convert Hex to ASCII *****"); 051 System.out.println("Hex : " + hex); 052 System.out.println("ASCII : " + strToHex.convertHexToString(hex)); 053 } 054}