0

I'm using the Deflater class to compress some String.

I need to convert that ascii String to a hexadecimal String. How do I convert it back to ascii String so that I can decompress using Inflater to receive my original String?

My problem is that the backwards conversion doesn't equal the original due to the encoding (?) or something.

Test code:

String compressed = Compressor.compress("stackoverflow.com");
System.out.println("Compressed ascii: " + compressed);

String converted = Converter.asciiToHex(compressed);
System.out.println("Compressed hex: " + converted);

System.out.println("Compressed ascii: " + Converter.hexToAscii(converted));

Output:

Compressed ascii: xœ+.ILÎÎ/K-JËÉ/×KÎÏ
Compressed hex: 789c2b2e494ccece2f4b2d4acbc92fd74bcecf05003ff306f8
Compressed ascii: x?+.ILÎÎ/K-JËÉ/×KÎÏ

Notice how the 2nd character is a ? instead of œ? Why is not converted properly? How can it be fixed?

The "faulty" method:

public static String hexToAscii(String hex)
{
    StringBuilder output = new StringBuilder();
    for (int i = 0; i < hex.length(); i += 2)
    {
        String str = hex.substring(i, i + 2);
        output.append((char) Integer.parseInt(str, 16));
    }

    return output.toString();
}
Bully WiiPlaza
  • 462
  • 1
  • 6
  • 16
  • I can't see what compress and asciiToHex are doing but it's probably a character set issue. Have you looked at the deflator example? http://docs.oracle.com/javase/7/docs/api/java/util/zip/Deflater.html – Toaster Jun 20 '14 at 03:37
  • @Colin: Compress means deflating the String and yes, it's working properly and is similar to the Oracle example. asciiToHex() converts the deflated String to hexadecimal String like seen in the output above. Any suggestions on resolving the character set issue therefore? It's most likely the cause. – Bully WiiPlaza Jun 20 '14 at 09:46
  • You might have a look here - http://stackoverflow.com/questions/81323/changing-the-default-encoding-for-stringbyte – Toaster Jun 23 '14 at 10:36
  • Also, this utility can detect the string encoding https://code.google.com/p/juniversalchardet/ – Toaster Jun 24 '14 at 12:03

0 Answers0