UTF-16 小解
UTF-16(16-bit Unicode Transformation Format)是一种针对 Unicode 的可变长度字符编码。见 UTF-16。
Unicode 的编码空间可划分为 17 个平面(plane),每个平面包含 65536 个码位。第一个平面称为基本多语言平面(BMP,Plane 0),其他平面称为辅助平面。
Unicode 基本平面与辅助平面
| Plane | Number of bytes | First code point | Last code point |
|---|---|---|---|
| 基本平面 | 2 | U+0000 | U+FFFF |
| 辅助平面 | 4 | U+10000 | U+10FFFF |
其中:基本平面(BMP)包含大部分常用字(如大部分汉字);辅助平面包含 emoji 等。
转化过程
- 将数据转化为 unicode 的 codePoint(如
str.codePointAt(0)) - 若 unicode 小于 U+10000,则直接返回,为 UTF-16 编码
- 若 unicode 大于 U+10000,则分为两个 UTF-16 编码:(codePoint - 0x10000) / 1024 + 0xD800 与 ((codePoint - 0x10000) % 1024) + 0xDC00
例如「🍉」:codePoint 0x1f349,减 0x10000 得 0x0f349,高位 0xd83c,低位 0xdf49。