Java Data Type How to - Change a hexadecimal number to its string equivalent








Question

We would like to know how to change a hexadecimal number to its string equivalent.

Answer

//from  w  w w.j a  va 2 s. co m
public class Main {

  public static void main(String[] args) throws Exception {
    String str = stringToHex("help");
    System.out.println(str);
    String str1 = convertHexToString(str);
    System.out.println(str1);
  }

  static String stringToHex(String str) {
    char[] chars = str.toCharArray();
    StringBuffer strBuffer = new StringBuffer();
    for (int i = 0; i < chars.length; i++) {
      strBuffer.append(Integer.toHexString((int) chars[i]));
    }
    return strBuffer.toString();
  }

  public static String convertHexToString(String hex) {

    StringBuilder sb = new StringBuilder();
    StringBuilder temp = new StringBuilder();

    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);
      temp.append(decimal);
    }
    return sb.toString();
  }

}