UTF-16转换给出错误的十六进制值

问题描述 投票:0回答:2

代码段是:

String str = "h";
StringBuffer buf = new StringBuffer();
byte[] bytes = str.getBytes("UTF-16BE");
for (int i = 0; i < bytes.length; i++) {
    String byteAsHex = Integer.toHexString(bytes[i]);
    buf.append(byteAsHex);
}
System.out.println(buf.toString());

输出为:068,其中LATIN SMALL LETTER H为0068。

你能不能告诉我为什么缺少领先0?

java unicode utf-16 utf
2个回答
3
投票

发生这种情况是因为Integer.toHexString()将始终返回数字的最短可能表示,即没有任何前导零。所以,在你的情况下,你有一个2字节的数组:[0, 0x68]Integer.toHexString()被调用两次,第一次返回0,第二次返回68

为了解决这个问题,如果字符串长度为1,则需要在'0'返回的每个字符串前面添加Integer.toHexString()


3
投票

这是因为Integer.toHexString(0)导致"0",但不是"00"

您可以在更换时解决此问题

Integer.toHexString(bytes[i])

通过

String.format("%02x", bytes[i])
© www.soinside.com 2019 - 2024. All rights reserved.