假设我将 Java 字符数组 (char[]) 实例编码为字节:
Say that I would encode a Java character array (char[]) instance as bytes:
这会始终创建有效的 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)编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
“Char 不能被取消引用"错误quot;Char cannot be dereferencedquot; error(“Char 不能被取消引用错误)
Java Switch 语句 - 是“或"/“和"可能的?Java Switch Statement - Is quot;orquot;/quot;andquot; possible?(Java Switch 语句 - 是“或/“和可能的?)
Java替换字符串特定位置的字符?Java Replace Character At Specific Position Of String?(Java替换字符串特定位置的字符?)
具有 int 和 char 操作数的三元表达式的类型是什么What is the type of a ternary expression with int and char operands?(具有 int 和 char 操作数的三元表达式的类型是什么?)
读取文本文件并存储出现的每个字符Read a text file and store every single character occurrence(读取文本文件并存储出现的每个字符)
为什么我需要在 byte 和 short 上显式转换 char 原语Why do I need to explicitly cast char primitives on byte and short?(为什么我需要在 byte 和 short 上显式转换 char 原语?)