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

时间:2018-09-15 19:56:07

标签: java unicode utf-16 utf

代码段是:

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,其中拉丁文小写字母H为0068。

能否请您告诉我为什么前导0丢失了?

2 个答案:

答案 0 :(得分:3)

之所以会这样,是因为Integer.toHexString()将始终返回数字的最短表示形式,即没有任何前导零。因此,在您的情况下,您有2个字节的数组:[0, 0x68]Integer.toHexString()被调用两次,第一次返回0,第二次返回{{1} }。

为解决此问题,如果字符串长度为1,则需要在68返回的每个字符串前加上'0'

答案 1 :(得分:3)

这是因为Integer.toHexString(0)的结果是"0",而不是"00"

更换时可以解决此问题

Integer.toHexString(bytes[i])

作者

String.format("%02x", bytes[i])