rco*_*ini -1 java hex ascii utf-8
我有字符串 String hex = "6174656ec3a7c3a36f";,我想得到String output = "atenção"但在我的测试中我只得到 String output = "aten????o";
我做错了什么?
String hex = "6174656ec3a7c3a36f";
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));
}
System.out.println(output); //here is the output "aten????o"
Run Code Online (Sandbox Code Playgroud)
考虑
String hex = "6174656ec3a7c3a36f"; // AAA
ByteBuffer buff = ByteBuffer.allocate(hex.length()/2);
for (int i = 0; i < hex.length(); i+=2) {
buff.put((byte)Integer.parseInt(hex.substring(i, i+2), 16));
}
buff.rewind();
Charset cs = Charset.forName("UTF-8"); // BBB
CharBuffer cb = cs.decode(buff); // BBB
System.out.println(cb.toString()); // CCC
Run Code Online (Sandbox Code Playgroud)
哪个印刷品: atenção
基本上,您的十六进制字符串表示以UTF-8编码时表示字符串atenção中字符的字节的十六进制编码.
要解码:
您的十六进制字符串似乎表示 UTF-8 字符串,而不是 ISO-8859-1。
我可以这样说的原因是,如果它是 ISO-8859-1,那么每个字符将有两个十六进制数字。您的十六进制字符串有 18 个字符,但您的预期输出只有 7 个字符。因此,十六进制字符串必须是可变宽度编码,而不是像 ISO-8859-1 那样每个字符一个字节。
以下程序产生输出: atenção
String hex = "6174656ec3a7c3a36f";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (int i = 0; i < hex.length(); i += 2) {
String str = hex.substring(i, i + 2);
int byteVal = Integer.parseInt(str, 16);
baos.write(byteVal);
}
String s = new String(baos.toByteArray(), Charset.forName("UTF-8"));
Run Code Online (Sandbox Code Playgroud)
如果您更改UTF-8为ISO-8859-1,您将看到:atenção。
| 归档时间: |
|
| 查看次数: |
14291 次 |
| 最近记录: |