现在的位置: 首页 > 综合 > 正文

4字节UTF16编码和对C++/Java的影响

2017年12月12日 ⁄ 综合 ⁄ 共 980字 ⁄ 字号 评论关闭

UTF16也可以占据4个byte

不要被UTF16这个名字骗了,UTF16编码也有可能占据4个byte。

比如,把下面的四个字符,用Notepad工具选择UTF16编码保存为txt文件就可以发现,每个字符都占据了4个bytes。

原因是,在远古时代,unicode字符的code point的范围是0x0000-0xffff,因此UTF16编码也都是16位。但后来unicode的code point可以超过16位了(0x0-0x10FFFF),UTF16编码也与时俱进,code point小于0xffff的字符仍然占据2Bytes,超过的就用4个bytes表示。

C++与UTF16

VC下,sizeof(wchar_t) = 2,因此无法表示所有的unicode字符。但是gcc下sizeof(wchar_t) == 4,这个才是完善的。

Java与UTF16

Java中,char类型虽然采用UTF16编码,但它只占据两个byte,因此无法表示一些特殊字符。
以下是JVM规范对char类型的描述:
"char,  whose  values  are  16-bit  unsigned  integers  representing  Unicode  code
points in the Basic Multilingual Plane, encoded with UTF-16, and whose default
value is the null code point ('\u0000')."

Java中的String类型也采用UTF16编码,但它不受两个byte的限制,以下为javadoc对String的描述:
"A String represents a string in the UTF-16 format in which supplementary characters
are represented by surrogate pairs (see the section Unicode Character Representations
in the Character class for more information). Index values refer to char code units,
so a supplementary character uses two positions in a String."
 
以下为相关的测试代码(csdn对特殊字符有限制,所以采用了图片格式):

抱歉!评论已关闭.