piątek, 13 kwietnia 2012

StringToHex, HexToString

czesto sie tego szuka, szybko sie znajduje... ale zawsze mozna szybciej ;]


 public synchronized static 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 synchronized static String convertHexToString(String hex) {

  StringBuilder sb = new StringBuilder();

  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);

  }

  return sb.toString();
 }

Kod jest skopiowany z czyjegos bloga, dobre pare miechow temu, wiec niestety odnosnika nie bedzie

Brak komentarzy:

Prześlij komentarz