Unicode简介

时间:2023-03-09 01:58:56
Unicode简介

计算机只能处理二进制,因此需要把文字表示为二进制才能被计算机理解和识别。
一般的做法是为每一个字母或汉字分配一个id,然后用二进制表示这个id,存在内存或磁盘中。计算机可以根据二进制数据知道这个id是什么,然后再根据id来知道二进制数据表示的是什么字母或汉字。
Unicode做的事情是为每一个字母或汉字分配id。
UTF-8、UTF-16、UTF-32是三种把Unicode 的code point表示为二进制的方法,一般我们称之为编码格式。

Unicode Standard包括哪些字符(Characters)

Unicode标准为所有的主流语言的字符指定了码位,包括西欧、中东、东亚的很多语言。此外,还包括标点符号、变音符号、数学符号、科技符号、箭头、装饰符号、emoji等。
最常用的字符在最起始的64K个code point中,这部分codespace叫做基本多语言平面(basic multilingual plane),简称BMP。除此之外,还包括16个其他的supplementary planes供其他字符使用。
Unicode为个人保留了一些code point,厂商或个人可以指定自己的字符或符号。在BMP中有6400个private的code point,在supplementary plane有131,068个保留的code point。

编码格式

即把code point编码为二进制的方法。
先看下code unit的概念。

The minimal bit combination that can represent a unit of encoded text for processing or interchange. The Unicode Standard uses 8-bit code units in the UTF-8 encoding form, 16-bit code units in the UTF-16 encoding form, and 32-bit code units in the UTF-32 encoding form.

  • UTF-8
    把Unicode字符表示为变长的比特,和ASCII码完美兼容。也就是说对于ASCII码,用一个字节表示,其他字符用2个或者更多个字节表示。code unit的长度是8bit。
  • UTF-16
    常用与存储空间和获取字符效率需要取得平衡的场景。常用的字符用16bit(一个code unit)编码,其他的用一对code unit编码(pairs of 16-bit code units)。
  • UTF-32
    用户存储空间不是问题,需要等宽的code unit的场景。每一个Unicode字符被表示为32bit。

定义文本的元素(Defining Elements of Text)

文本的组成元素在不同的场景下有所不同。比如在历史上的西班牙语,“ll”是一个单独的元素,但是当这个字符在输入时,“ll”是两个“l”的组合。
Unicode定义了code elements(通常意义的“characters”),即用于计算机文本处理的基本元素。在上面的例子中,把两个“l”合并为一个“ll”是文本处理软件的事情。

字符序列(Character Sequences)

有时候,text element可以由多个character表示,这些多个character组成的序列叫做combining character sequences
比如说“â”可以表示为 “a”和“^”的组合。Unicode定义了这些组合的顺序,一般是基本的字符“a”在前,紧跟着一个non-spacing(不占空间?)的符号“^”。
一些字符按顺序排列可以表示一个单独的字符,叫做precomposed charactercomposite characterdecomposable character。比如“ü”有一个单独的code point U+00FC,也可以表示为基本字母“u”(U+0075)后跟着一个non-spacing字符“¨”(U+0308)。这样子便于排序,因为有时候字母的变形并不影响排序。
也就是说,一个字符有多个表示方法,Unicode又给出了判断字符是否相等的方法。

Programs should always compare canonical-equivalent Unicode strings as equal (For the details of this requirement, see Section 3.2, Conformance Requirements and Section 3.7, Decomposition, in The Unicode Standard). One of the easiest ways to do this is to use a normalized form for the strings: if strings are transformed into their normalized forms, then canonical-equivalent ones will also have precisely the same binary representation. The Unicode Standard provides well-defined normalization forms that can be used for this: NFC and NFD.

参考

The Unicode® Standard: A Technical Introduction
Unicode equivalence wiki
CANONICAL EQUIVALENCE IN APPLICATIONS
FAQ Normalization