我正在玩 this question 的已接受答案中的代码片段.我只是添加了一个字节数组来使用 UTF-16,如下所示:
final char[] chars = Character.toChars(0x1F701);
final String s = new String(chars);
final byte[] asBytes = s.getBytes(StandardCharsets.UTF_8);
final byte[] asBytes16 = s.getBytes(StandardCharsets.UTF_16);
chars
有 2 个元素,在 Java 中这意味着两个 16 位整数(因为代码点在 BMP 之外)。
asBytes
有 4 个元素,对应 32 位,这是我们需要从 chars 中表示两个 16 位整数的内容,所以它是有道理的。
asBytes16
有 6 个元素,这让我很困惑。当 32 位足以表示此 unicode 字符时,为什么我们最终会多出 2 个字节?
最佳答案
UTF-16 字节以 Byte order mark 开头FEFF
表示该值以大端编码。根据 wiki BOM 也用于区分 UTF-16 和 UTF-8:
Neither of these sequences is valid UTF-8, so their presence indicates that the file is not encoded in UTF-8.
您可以根据 this answer 将 byte[]
转换为十六进制编码的 String
:
asBytes = F09F9C81
asBytes16 = FEFFD83DDF01
关于java - 为什么这个 unicode 字符以 UTF-16 编码结束为 6 个字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54038562/