08/11/2013

[Java] String to Hexadecimal and viceversa

To convert a String to its hex representation in Java, simply:

 public static String string2Hex(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();  
  }  
   


and in the other direction:

 public static String hex2String(String hex){  
         
       StringBuilder sb = new StringBuilder();  
         
       /*two hex characters for each ASCII one*/  
       for( int i=0; i<hex.length()-1; i+=2 ){  
    
            String output = hex.substring(i, (i + 2));  
            int decimal = Integer.parseInt(output, 16);  
            sb.append((char)decimal);  
       }  
    
       return sb.toString();  
  }  
   

No comments:

Post a Comment

With great power comes great responsibility