Is a Java char array always a valid UTF-16 (Big Endian) encoding?(Java char 数组是否始终是有效的 UTF-16(Big Endian)编码?)
问题描述
假设我将 Java 字符数组 (char[]
) 实例编码为字节:
Say that I would encode a Java character array (char[]
) instance as bytes:
- 每个字符使用两个字节
- 使用大端编码(将最高有效 8 位存储在最左边的字节中,将最低有效 8 位存储在最右边的字节中)
这会始终创建有效的 UTF-16BE 编码吗?如果不是,哪些代码点会导致编码无效?
Would this always create a valid UTF-16BE encoding? If not, which code points will result in an invalid encoding?
这个问题与 这个关于 Java char 类型的问题 和 这个关于Java字符串内部表示的问题.
推荐答案
没有.您可以创建包含您想要的任何 16 位值的 char
实例——没有任何东西将它们限制为有效的 UTF-16 代码单元,也没有将它们的数组限制为有效的 UTF-16 序列.甚至 String
也不要求其数据是有效的 UTF-16:
No. You can create char
instances that contain any 16-bit value you desire---there is nothing that constrains them to be valid UTF-16 code units, nor constrains an array of them to be a valid UTF-16 sequence. Even String
does not require that its data be valid UTF-16:
char data[] = {'uD800', 'b', 'c'}; // Unpaired lead surrogate
String str = new String(data);
Unicode 的 第 3 章 中规定了有效 UTF-16 数据的要求标准(基本上,一切都必须是 Unicode 标量值,并且所有代理项必须正确配对).您可以使用 CharsetEncoder
测试 char
数组是否是有效的 UTF-16 序列,并将其转换为 UTF-16BE(或 LE)字节序列:
The requirements for valid UTF-16 data are set out in Chapter 3 of the Unicode Standard (basically, everything must be a Unicode scalar value, and all surrogates must be correctly paired). You can test if a char
array is a valid UTF-16 sequence, and turn it into a sequence of UTF-16BE (or LE) bytes, by using a CharsetEncoder
:
CharsetEncoder encoder = Charset.forName("UTF-16BE").newEncoder();
ByteBuffer bytes = encoder.encode(CharBuffer.wrap(data)); // throws MalformedInputException
(如果你有字节,同样使用 CharsetDecoder
.)
(And similarly using a CharsetDecoder
if you have bytes.)
这篇关于Java char 数组是否始终是有效的 UTF-16(Big Endian)编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java char 数组是否始终是有效的 UTF-16(Big Endian)编码


基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01