`
huangqinqin
  • 浏览: 360408 次
  • 性别: Icon_minigender_2
  • 来自: 福州
社区版块
存档分类
最新评论

Hex ASCII间的转换

    博客分类:
  • java
 
阅读更多
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));
  }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics