3

Hex to ASCII showing a different result to correct the implementation of PHP

 2 years ago
source link: https://www.codesd.com/item/hex-to-ascii-showing-a-different-result-to-correct-the-implementation-of-php.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Hex to ASCII showing a different result to correct the implementation of PHP

advertisements

I needed a method that would convert hex to ascii, and most seem to be a variation of the following:

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

The idea is to look at

hexToAscii("51d37bdd871c9e1f4d5541be67a6ab625e32028744d7d4609d0c37747b40cd2d");

If I print the result out, I get

-Í@{t7?`Ô×D?2^b«¦g¾AUM??Ý{ÓQ.

This is not the result I am needing though. A friend got the correct result in PHP which was the string reverse of the following:

QÓ{݇žMUA¾g¦«b^2‡D×Ô`7t{@Í-

There are clearly characters that his hexToAscii function is encoding whereas mine is not. Not really sure why this is the case, but how can I implement this version in Java?


Assuming your input string is in, I would use a method like this

public static byte[] decode(String in) {
  if (in != null) {
    in = in.trim();
    List<Byte> bytes = new ArrayList<Byte>();
    char[] chArr = in.toCharArray();

    int t = 0;
    while (t + 1 < chArr.length) {
      String token = "" + chArr[t] + chArr[t + 1];
      // This subtracts 128 from the byte value.
      int b = Byte.MIN_VALUE
          + Integer.valueOf(token, 16);
      bytes.add((byte) b);
      t += 2;
    }
    byte[] out = new byte[bytes.size()];
    for (int i = 0; i < bytes.size(); ++i) {
      out[i] = bytes.get(i);
    }
    return out;
  }
  return new byte[] {};
}

And then you could use it like this

new String(decode("51d37bdd871c9e1f4d5541be67a6ab625e"
  +"32028744d7d4609d0c37747b40cd2d"))


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK