我使用Deflater类来压缩一些String。
我需要将ascii String转换为十六进制字符串。如何将其转换回ascii String以便我可以使用Inflater解压缩以接收我的原始字符串?
我的问题是,由于编码(?)或其他原因,向后转换与原始版本不相等。
测试代码:
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));
输出:
Compressed ascii: xœ+.ILÎÎ/K-JËÉ/×KÎÏ
Compressed hex: 789c2b2e494ccece2f4b2d4acbc92fd74bcecf05003ff306f8
Compressed ascii: x?+.ILÎÎ/K-JËÉ/×KÎÏ
请注意第二个字符是?
而不是œ
?为什么没有正确转换?如何解决?
"错误"方法:
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();
}