跳到主要内容

Unicode 转 UTF-16

快速尝试:

转化过程解析

Unicode
二进制
转换过程
UTF-16

UTF-16 小解

UTF-16(16-bit Unicode Transformation Format)是一种针对 Unicode 的可变长度字符编码。见 UTF-16。

Unicode 的编码空间可划分为 17 个平面(plane),每个平面包含 65536 个码位。第一个平面称为基本多语言平面(BMP,Plane 0),其他平面称为辅助平面。

Unicode 基本平面与辅助平面

PlaneNumber of bytesFirst code pointLast code point
基本平面2U+0000U+FFFF
辅助平面4U+10000U+10FFFF

其中:基本平面(BMP)包含大部分常用字(如大部分汉字);辅助平面包含 emoji 等。

转化过程

  1. 将数据转化为 unicode 的 codePoint(如 str.codePointAt(0))
  2. 若 unicode 小于 U+10000,则直接返回,为 UTF-16 编码
  3. 若 unicode 大于 U+10000,则分为两个 UTF-16 编码:(codePoint - 0x10000) / 1024 + 0xD800 与 ((codePoint - 0x10000) % 1024) + 0xDC00

例如「🍉」:codePoint 0x1f349,减 0x10000 得 0x0f349,高位 0xd83c,低位 0xdf49。