728x90
String -> Hex변환
Hex -> String변환
 
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));
  }
}
 
 
***** Convert ASCII to Hex *****
Original input : I Love Java!
Hex : 49204c6f7665204a61766121
 
***** Convert Hex to ASCII *****
Hex : 49204c6f7665204a61766121
Decimal : 7332761111181013274971189733
ASCII : I Love Java!

* 영어만된다. 한글 안됨. 그래서 패스

728x90

'JAVA' 카테고리의 다른 글

<fmt:formatNumber><fmt:parseNumber>  (0) 2013.02.01
bean:write 형변환  (0) 2013.02.01
자바 한글 UNICODE 변환 (특수문자안됨)  (0) 2013.01.16
자바 한글 unicode 변환 (테스트안해봄)  (0) 2013.01.16
자바 hashcode  (0) 2013.01.16

+ Recent posts