[转]wiki:UTF-8
原文:http://en.wikipedia.org/wiki/UTF-8
UTF-8 (U from Universal Character Set + Transformation Format—8-bit[1]) is a character encoding capable of encoding all possible characters (called code points) in Unicode. The encoding is variable-length and uses 8-bit code units. It was designed for backward compatibility with ASCII and to avoid the complications of endianness and byte order marks in UTF-16 and UTF-32.
UTF-8 has become the dominant character encoding for the World Wide Web, accounting for 81.4% of all Web pages in November 2014 (with most popular East Asian encoding at 1.4% and all of them combined under 5%).[3][2][4] The Internet Mail Consortium (IMC) recommends that all e-mail programs be able to display and create mail using UTF-8.[5] The W3C recommends UTF-8 as default encoding in their main standards (XML and HTML).
UTF-8 encodes each of the 1,112,064 valid code points in the Unicode code space (1,114,112 code points minus 2,048 surrogate code points) using one to four 8-bit bytes (a group of 8 bits is known as an octet in the Unicode Standard). Code points with lower numerical values (i.e. earlier code positions in the Unicode character set, which tend to occur more frequently) are encoded using fewer bytes. The first 128 characters of Unicode, which correspond one-to-one with ASCII, are encoded using a single octet with the same binary value as ASCII, making valid ASCII text valid UTF-8-encoded Unicode as well.
The official IANA code for the UTF-8 character encoding is UTF-8
.[6]
Contents
[hide]
History[edit]
By early 1992, the search was on for a good byte-stream encoding of multi-byte character sets. The draft ISO 10646 standard contained a non-required annex called UTF-1 that provided a byte-stream encoding of its 32-bit code points. This encoding was not satisfactory on performance grounds, but did introduce the notion that bytes in the range of 0–127 continue representing the ASCII characters in UTF, thereby providing backward compatibility with ASCII.
In July 1992, the X/Open committee XoJIG was looking for a better encoding. Dave Prosser of Unix System Laboratories submitted a proposal for one that had faster implementation characteristics and introduced the improvement that 7-bit ASCII characters would only represent themselves; all multibyte sequences would include only bytes where the high bit was set. This original proposal, the File System Safe UCS Transformation Format (FSS-UTF), was similar in concept to UTF-8, but lacked the crucial property of self-synchronization.[7][8]
In August 1992, this proposal was circulated by an IBM X/Open representative to interested parties. Ken Thompson of the Plan 9 operating system group at Bell Labs made a small but crucial modification to the encoding, making it very slightly less bit-efficient than the previous proposal but allowing it to be self-synchronizing, meaning that it was no longer necessary to read from the beginning of the string to find code point boundaries. Thompson's design was outlined on September 2, 1992, on a placemat in a New Jersey diner with Rob Pike. In the following days, Pike and Thompson implemented it and updated Plan 9 to use it throughout, and then communicated their success back to X/Open.[7]
UTF-8 was first officially presented at the USENIX conference in San Diego, from January 25 to 29, 1993.
Google reported that in 2008 UTF-8 (misleadingly labelled "Unicode") became the most common encoding for HTML files.[9][10]
Description[edit]
The design of UTF-8 can be seen in this table of the scheme as originally proposed by Dave Prosser and subsequently modified by Ken Thompson (the x
characters are replaced by the bits of the code point):
Bits of code point | First code point | Last code point | Bytes in sequence | Byte 1 | Byte 2 | Byte 3 | Byte 4 | Byte 5 | Byte 6 |
---|---|---|---|---|---|---|---|---|---|
7 | U+0000 | U+007F | 1 | 0xxxxxxx |
|||||
11 | U+0080 | U+07FF | 2 | 110xxxxx |
10xxxxxx |
||||
16 | U+0800 | U+FFFF | 3 | 1110xxxx |
10xxxxxx |
10xxxxxx |
|||
21 | U+10000 | U+1FFFFF | 4 | 11110xxx |
10xxxxxx |
10xxxxxx |
10xxxxxx |
||
The patterns below are not part of UTF-8, but were part of the first specification. | |||||||||
26 | U+200000 | U+3FFFFFF | 5 | 111110xx |
10xxxxxx |
10xxxxxx |
10xxxxxx |
10xxxxxx |
|
31 | U+4000000 | U+7FFFFFFF | 6 | 1111110x |
10xxxxxx |
10xxxxxx |
10xxxxxx |
10xxxxxx |
10xxxxxx |
The original specification covered numbers up to 31 bits (the original limit of the Universal Character Set). In November 2003, UTF-8 was restricted by RFC 3629 to end at U+10FFFF
, in order to match the constraints of the UTF-16character encoding. This removed all 5- and 6-byte sequences, and about half of the 4-byte sequences.
The salient features of this scheme are as follows:
- Backward compatibility: One-byte codes are used only for the ASCII values 0 through 127. In this case the UTF-8 code has the same value as the ASCII code. The high-order bit of these codes is always 0. This means that UTF-8 can be used for parsers expecting 8-bit extended ASCII even if they are not designed for UTF-8.
- Clear distinction between multi-byte and single-byte characters: Code points larger than 127 are represented by multi-byte sequences, composed of a leading byte and one or more continuation bytes. The leading byte has two or more high-order 1s followed by a 0, while continuation bytes all have '10' in the high-order position.
- Self synchronization: Single bytes, leading bytes, and continuation bytes do not share values. This makes the scheme self-synchronizing, allowing the start of a character to be found by backing up at most five bytes (three bytes in actual UTF‑8 per RFC 3629 restriction, see above).
Bit patterns0xxxxxxx
and11xxxxxx
are synchronizing words used to mark the beginning of the next valid character. - Clear indication of code sequence length: The number of high-order 1s in the leading byte of a multi-byte sequence indicates the number of bytes in the sequence, so that the length of the sequence can be determined without examining the continuation bytes.
- Code structure: The remaining bits of the encoding are used for the bits of the code point being encoded, padded with high-order 0s if necessary. The high-order bits go in the lead byte, lower-order bits in succeeding continuation bytes. The number of bytes in the encoding is the minimum required to hold all the significant bits of the code point.
The first 128 characters (US-ASCII) need one byte. The next 1,920 characters need two bytes to encode. This covers the remainder of almost all Latin alphabets, and also Greek, Cyrillic, Coptic, Armenian, Hebrew, Arabic, Syriac and Tānaalphabets, as well as Combining Diacritical Marks. Three bytes are needed for characters in the rest of the Basic Multilingual Plane (which contains virtually all characters in common use[11]). Four bytes are needed for characters in theother planes of Unicode, which include less common CJK characters, various historic scripts, mathematical symbols, and emoji (pictographic symbols).
Examples[edit]
Consider the encoding of the Euro sign, €.
- The Unicode code point for "€" is U+20AC.
- According to the scheme table above, this will take three bytes to encode, since it is between U+0800 and U+FFFF.
- Hexadecimal
20AC
is binary0010000010101100
. The two leading zeros are added because, as the scheme table shows, a three-byte encoding needs exactly sixteen bits from the code point. - Because it is a three-byte encoding, the leading byte starts with three 1s, then a 0 (
1110
...) - The remaining bits of this byte are taken from the code point (
11100010
), leaving ...000010101100
. - Each of the continuation bytes starts with
10
and takes six bits of the code point (so10000010
, then10101100
).
The three bytes 11100010
10000010
10101100
can be more concisely written in hexadecimal, as E2 82 AC
.
The following table summarises this conversion, as well as others with different lengths in UTF-8. The colors indicate how bits from the code point are distributed among the UTF-8 bytes. Additional bits added by the UTF-8 encoding process are shown in black.
Character | Binary code point | Binary UTF-8 | Hexadecimal UTF-8 | |
---|---|---|---|---|
$ | U+0024 |
0100100 |
00100100 |
24 |
¢ | U+00A2 |
000 10100010 |
11000010 10100010 |
C2 A2 |
€ | U+20AC |
00100000 10101100 |
11100010 10000010 10101100 |
E2 82 AC |
𤭢 | U+24B62 |
00010 01001011 01100010 |
11110000 10100100 10101101 10100010 |
F0 A4 AD A2 |
Codepage layout[edit]
_0 | _1 | _2 | _3 | _4 | _5 | _6 | _7 | _8 | _9 | _A | _B | _C | _D | _E | _F | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0_ |
NUL 0000 0 |
SOH 0001 1 |
STX 0002 2 |
ETX 0003 3 |
EOT 0004 4 |
ENQ 0005 5 |
ACK 0006 6 |
BEL 0007 7 |
BS 0008 8 |
HT 0009 9 |
LF 000A 10 |
VT 000B 11 |
FF 000C 12 |
CR 000D 13 |
SO 000E 14 |
SI 000F 15 |
1_ |
DLE 0010 16 |
DC1 0011 17 |
DC2 0012 18 |
DC3 0013 19 |
DC4 0014 20 |
NAK 0015 21 |
SYN 0016 22 |
ETB 0017 23 |
CAN 0018 24 |
EM 0019 25 |
SUB 001A 26 |
ESC 001B 27 |
FS 001C 28 |
GS 001D 29 |
RS 001E 30 |
US 001F 31 |
2_ |
SP 0020 32 |
! 0021 33 |
" 0022 34 |
# 0023 35 |
$ 0024 36 |
% 0025 37 |
& 0026 38 |
' 0027 39 |
( 0028 40 |
) 0029 41 |
* 002A 42 |
+ 002B 43 |
, 002C 44 |
- 002D 45 |
. 002E 46 |
/ 002F 47 |
3_ |
0 0030 48 |
1 0031 49 |
2 0032 50 |
3 0033 51 |
4 0034 52 |
5 0035 53 |
6 0036 54 |
7 0037 55 |
8 0038 56 |
9 0039 57 |
: 003A 58 |
; 003B 59 |
< 003C 60 |
= 003D 61 |
> 003E 62 |
? 003F 63 |
4_ |
@ 0040 64 |
A 0041 65 |
B 0042 66 |
C 0043 67 |
D 0044 68 |
E 0045 69 |
F 0046 70 |
G 0047 71 |
H 0048 72 |
I 0049 73 |
J 004A 74 |
K 004B 75 |
L 004C 76 |
M 004D 77 |
N 004E 78 |
O 004F 79 |
5_ |
P 0050 80 |
Q 0051 81 |
R 0052 82 |
S 0053 83 |
T 0054 84 |
U 0055 85 |
V 0056 86 |
W 0057 87 |
X 0058 88 |
Y 0059 89 |
Z 005A 90 |
[ 005B 91 |
\ 005C 92 |
] 005D 93 |
^ 005E 94 |
_ 005F 95 |
6_ |
` 0060 96 |
a 0061 97 |
b 0062 98 |
c 0063 99 |
d 0064 100 |
e 0065 101 |
f 0066 102 |
g 0067 103 |
h 0068 104 |
i 0069 105 |
j 006A 106 |
k 006B 107 |
l 006C 108 |
m 006D 109 |
n 006E 110 |
o 006F 111 |
7_ |
p 0070 112 |
q 0071 113 |
r 0072 114 |
s 0073 115 |
t 0074 116 |
u 0075 117 |
v 0076 118 |
w 0077 119 |
x 0078 120 |
y 0079 121 |
z 007A 122 |
{ 007B 123 |
| 007C 124 |
} 007D 125 |
~ 007E 126 |
DEL 007F 127 |
8_ |
• +00 128 |
• +01 129 |
• +02 130 |
• +03 131 |
• +04 132 |
• +05 133 |
• +06 134 |
• +07 135 |
• +08 136 |
• +09 137 |
• +0A 138 |
• +0B 139 |
• +0C 140 |
• +0D 141 |
• +0E 142 |
• +0F 143 |
9_ |
• +10 144 |
• +11 145 |
• +12 146 |
• +13 147 |
• +14 148 |
• +15 149 |
• +16 150 |
• +17 151 |
• +18 152 |
• +19 153 |
• +1A 154 |
• +1B 155 |
• +1C 156 |
• +1D 157 |
• +1E 158 |
• +1F 159 |
A_ |
• +20 160 |
• +21 161 |
• +22 162 |
• +23 163 |
• +24 164 |
• +25 165 |
• +26 166 |
• +27 167 |
• +28 168 |
• +29 169 |
• +2A 170 |
• +2B 171 |
• +2C 172 |
• +2D 173 |
• +2E 174 |
• +2F 175 |
B_ |
• +30 176 |
• +31 177 |
• +32 178 |
• +33 179 |
• +34 180 |
• +35 181 |
• +36 182 |
• +37 183 |
• +38 184 |
• +39 185 |
• +3A 186 |
• +3B 187 |
• +3C 188 |
• +3D 189 |
• +3E 190 |
• +3F 191 |
2-byte C_ |
2-byte inval (0000) 192 |
2-byte inval (0040) 193 |
Latin-1 0080 194 |
Latin-1 00C0 195 |
Latin Ext-A 0100 196 |
Latin Ext-A 0140 197 |
Latin Ext-B 0180 198 |
Latin Ext-B 01C0 199 |
Latin Ext-B 0200 200 |
IPA 0240 201 |
IPA 0280 202 |
Spaci Modif 02C0 203 |
Combi Diacr 0300 204 |
Combi Diacr 0340 205 |
Greek 0380 206 |
Greek 03C0 207 |
2-byte D_ |
Cyril 0400 208 |
Cyril 0440 209 |
Cyril 0480 210 |
Cyril 04C0 211 |
Cyril 0500 212 |
Armen 0540 213 |
Hebrew 0580 214 |
Hebrew 05C0 215 |
Arabic 0600 216 |
Arabic 0640 217 |
Arabic 0680 218 |
Arabic 06C0 219 |
Syriac 0700 220 |
Arabic 0740 221 |
Thaana 0780 222 |
N'Ko 07C0 223 |
3-byte E_ |
Indic 0800* 224 |
Misc. 1000 225 |
Symbol 2000 226 |
Kana CJK 3000 227 |
CJK 4000 228 |
CJK 5000 229 |
CJK 6000 230 |
CJK 7000 231 |
CJK 8000 232 |
CJK 9000 233 |
Asian A000 234 |
Hangul B000 235 |
Hangul C000 236 |
Hangul Surr D000 237 |
Priv Use E000 238 |
Forms F000 239 |
4-byte F_ |
Ancient Sym,CJK 10000* 240 |
unall 40000 241 |
unall 80000 242 |
Tags Priv C0000 243 |
Priv Use 100000 244 |
4-byte inval 140000 245 |
4-byte inval 180000 246 |
4-byte inval 1C0000 247 |
5-byte inval 200000* 248 |
5-byte inval 1000000 249 |
5-byte inval 2000000 250 |
5-byte inval 3000000 251 |
6-byte inval 4000000* 252 |
6-byte inval 40000000 253 |
254 |
255 |
Legend: Yellow cells are control characters, blue cells are punctuation, purple cells are digits and green cells are ASCII letters.
Orange cells with a large dot are continuation bytes. The hexadecimal number shown after a "+" plus sign is the value of the 6 bits they add.
White cells are the start bytes for a sequence of multiple bytes, the length shown at the left edge of the row. The text shows the Unicode blocks encoded by sequences starting with this byte, and the hexadecimal code point shown in the cell is the lowest character value encoded using that start byte. When a start byte could form both overlong and valid encodings, the lowest non-overlong-encoded code point is shown, marked by an asterisk "*".
Red cells must never appear in a valid UTF-8 sequence. The first two (C0 and C1) could only be used for overlong encoding of basic ASCII characters (i.e., trying to encode a 7-bit ASCII value between 0 and 127 using 2 bytes instead of 1). The remaining red cells indicate start bytes of sequences that could only encode numbers larger than the 0x10FFFF limit of Unicode. The byte 244 (hex 0xF4) could also encode some values greater than 0x10FFFF; such a sequence would also be invalid if the subsequent bytes attempted to encode a value higher than 0x10FFFF.
Overlong encodings[edit]
In principle, it would be possible to inflate the number of bytes in an encoding by padding the code point with leading 0s. To encode the Euro sign € from the above example in four bytes instead of three, it could be padded with leading 0s until it was 21 bits long—000 000010 000010 101100
, and encoded as 11110000
10000010
10000010
10101100
(or F0
82
82
AC
in hexadecimal). This is called an overlong encoding.
The standard specifies that the correct encoding of a code point use only the minimum number of bytes required to hold the significant bits of the code point. Longer encodings are called overlong and are not valid UTF-8 representations of the code point. This rule maintains a one-to-one correspondence between code points and their valid encodings, so that there is a unique valid encoding for each code point, this makes string comparisons and searches well-defined.
Modified UTF-8 uses the 2-byte overlong encoding of U+0000 (the NUL character), 11000000
10000000
(hex C0
80
), rather than 00000000
(hex 00
). This allows the byte 00
to be used as a string terminator.
Invalid byte sequences[edit]
Not all sequences of bytes are valid UTF-8. A UTF-8 decoder should be prepared for:
- the red invalid bytes in the above table
- an unexpected continuation byte
- a start byte not followed by enough continuation bytes
- an Overlong Encoding as described above
- A 4-byte sequence (starting with 0xF4) that decodes to a value greater than U+10FFFF
Many earlier decoders would happily try to decode these. Carefully crafted invalid UTF-8 could make them either skip or create ASCII characters such as NUL, slash, or quotes. Invalid UTF-8 has been used to bypass security validations in high profile products including Microsoft's IIS web server[12] and Apache's Tomcat servlet container.[13]
RFC 3629 states "Implementations of the decoding algorithm MUST protect against decoding invalid sequences."[14] The Unicode Standard requires decoders to "...treat any ill-formed code unit sequence as an error condition. This guarantees that it will neither interpret nor emit an ill-formed code unit sequence."
Many UTF-8 decoders throw exceptions on encountering errors.[15] This can turn what would otherwise be harmless errors (producing a message such as "no such file") into a denial of service bug. Early versions of Python 3.0 would exit immediately if the command line or environment variables contained invalid UTF-8,[16] making it impossible to handle such errors.
More recent converters translate the first byte of an invalid sequence to a replacement character and continue parsing with the next byte. These error bytes will always have the high bit set. This avoids denial-of-service bugs, and it is very common in text rendering such as browser display, since mangled text is probably more useful than nothing for helping the user figure out what the string was supposed to contain. Popular replacements include:
- The replacement character "�" (U+FFFD)
- The invalid Unicode code points U+DC80–U+DCFF where the low 8 bits are the byte's value.[17] Sometimes it is called UTF-8B[18] (where the B stands for Binary)
- The Unicode code points U+0080–U+00FF with the same value as the byte, thus interpreting the bytes according to ISO-8859-1[citation needed]
- The Unicode code point for the character represented by the byte in CP1252,[citation needed] which is similar to using ISO-8859-1, except that some characters in the range 0x80–0x9F are mapped into different Unicode code points. For example, 0x80 becomes the Euro sign, U+20AC.
These replacement algorithms are "lossy", as more than one sequence is translated to the same code point. This means that it would not be possible to reliably convert back to the original encoding, therefore losing information.
The large number of invalid byte sequences provides the advantage of making it easy to have a program accept both UTF-8 and legacy encodings such as ISO-8859-1. Thus, the software can check for UTF-8 correctness, and if that fails assume the input to be in the legacy encoding. It is technically true that this may detect an ISO-8859-1 string as UTF-8, but this is very unlikely if it contains any 8-bit bytes as they all have to be in unusual patterns of two or more in a row, such as "£".
Invalid code points[edit]
According to the UTF-8 definition (RFC 3629) the high and low surrogate halves used by UTF-16 (U+D800 through U+DFFF) are not legal Unicode values, and their UTF-8 encoding should be treated as an invalid byte sequence.
Whether an actual application should do this is debatable, as it makes it impossible to store invalid UTF-16 (that is, UTF-16 with unpaired surrogate halves) in a UTF-8 string. This is necessary to store unchecked UTF-16 such as Windows filenames as UTF-8. It is also incompatible with CESU encoding (described below).
Sample code[edit]
This code assumes ungetc
can be called more than once. It translates any encoding errors into 0xDCxx, where xx is the value of the error byte.
void write_utf8(unsigned code_point)
{
if (code_point < 0x80) {
putchar(code_point);
} else if (code_point <= 0x7FF) {
putchar((code_point >> 6) + 0xC0);
putchar((code_point & 0x3F) + 0x80);
} else if (code_point <= 0xFFFF) {
putchar((code_point >> 12) + 0xE0);
putchar(((code_point >> 6) & 0x3F) + 0x80);
putchar((code_point & 0x3F) + 0x80);
} else if (code_point <= 0x10FFFF) {
putchar((code_point >> 18) + 0xF0);
putchar(((code_point >> 12) & 0x3F) + 0x80);
putchar(((code_point >> 6) & 0x3F) + 0x80);
putchar((code_point & 0x3F) + 0x80);
} else {
error("invalid code_point");
}
}
unsigned read_code_point_from_utf8()
{
int code_unit1, code_unit2, code_unit3, code_unit4;
code_unit1 = getchar();
if (code_unit1 < 0x80) {
return code_unit1;
} else if (code_unit1 < 0xC2) {
/* continuation or overlong 2-byte sequence */
goto ERROR1;
} else if (code_unit1 < 0xE0) {
/* 2-byte sequence */
code_unit2 = getchar();
if ((code_unit2 & 0xC0) != 0x80) goto ERROR2;
return (code_unit1 << 6) + code_unit2 - 0x3080;
} else if (code_unit1 < 0xF0) {
/* 3-byte sequence */
code_unit2 = getchar();
if ((code_unit2 & 0xC0) != 0x80) goto ERROR2;