3.4 Character encoding *¶
All computer data is stored as binary numbers, including characters of type char. To represent characters, we need a character set that assigns each character a unique binary number. The computer can then convert numbers to characters by looking them up.
3.4.1 ASCII character set¶
ASCII, short for American Standard Code for Information Interchange, was the earliest character set. It uses 7 bits (the lower 7 bits of a byte) per character, allowing up to 128 characters. As shown in Figure 3-6, ASCII includes uppercase and lowercase English letters, digits 0 ~ 9, punctuation, and control characters such as newlines and tabs.
Figure 3-6 ASCII codes
Description of Figure 3-6: ASCII characters and code table
Look up the binary representation by decimal code or character, and distinguish control characters from printable characters.
ASCII uses 7 bits to represent 128 characters, with codes ranging from 0 to 127. The figure displays binary values as 8-bit single bytes grouped into nibbles of 4 bits, with the highest bit fixed at 0; the table below merges the figure's four column panels into a single complete table ordered by increasing decimal code.
By code range: 0 to 31 and 127 are control characters, where 127 is DEL for delete (left blank in the figure's meaning column); 32 is the space character SP; 48 to 57 are the digits 0 to 9; 65 to 90 are uppercase letters A to Z; and 97 to 122 are lowercase letters a to z. Printable punctuation and symbols occupy 33 to 47, 58 to 64, 91 to 96, and 123 to 126.
The table’s meaning column uses the labels in the English figure. Code 14, SO (Shift out), selects an alternate character set; code 15, SI (Shift in), switches back to the original set. Code 27, ESC (Escape), can introduce an escape sequence. Codes 10 (LF, Line feed), 12 (FF, Form feed), and 13 (CR, Carriage return) control line breaks, page breaks, and returning to the start of a line, respectively.
A character glyph differs from its numeric code: the digit character 0 has code 48 (binary 0011 0000), whereas code 0 is the null character NUL (binary 0000 0000); both also differ from the space character SP (32) and the delete character DEL (127).
For the digit characters 0 to 9, the upper four bits are always 0011 and the lower four bits run from 0000 to 1001. Uppercase and lowercase forms of the same letter differ by 32, changing only the 6th bit from the right (weight 32): A is 65 (binary 0100 0001) and a is 97 (binary 0110 0001). For instance, to look up a newline, locate LF at decimal row 10 in the table below.
| Decimal | Binary | Character | Meaning (shown in figure) |
|---|---|---|---|
| 0 | 0000 0000 | NUL | Null |
| 1 | 0000 0001 | SOH | Start of heading |
| 2 | 0000 0010 | STX | Start of text |
| 3 | 0000 0011 | ETX | End of text |
| 4 | 0000 0100 | EOT | End of transmission |
| 5 | 0000 0101 | ENQ | Enquiry |
| 6 | 0000 0110 | ACK | Acknowledge |
| 7 | 0000 0111 | BEL | Bell |
| 8 | 0000 1000 | BS | Backspace |
| 9 | 0000 1001 | HT | Horizontal tab |
| 10 | 0000 1010 | LF | Line feed |
| 11 | 0000 1011 | VT | Vertical tab |
| 12 | 0000 1100 | FF | Form feed |
| 13 | 0000 1101 | CR | Carriage return |
| 14 | 0000 1110 | SO | Shift out |
| 15 | 0000 1111 | SI | Shift in |
| 16 | 0001 0000 | DLE | Data link escape |
| 17 | 0001 0001 | DC1 | Device control 1 |
| 18 | 0001 0010 | DC2 | Device control 2 |
| 19 | 0001 0011 | DC3 | Device control 3 |
| 20 | 0001 0100 | DC4 | Device control 4 |
| 21 | 0001 0101 | NAK | Negative acknowledge |
| 22 | 0001 0110 | SYN | Synchronous idle |
| 23 | 0001 0111 | ETB | End of transmission block |
| 24 | 0001 1000 | CAN | Cancel |
| 25 | 0001 1001 | EM | End of medium |
| 26 | 0001 1010 | SUB | Substitute |
| 27 | 0001 1011 | ESC | Escape |
| 28 | 0001 1100 | FS | File separator |
| 29 | 0001 1101 | GS | Group separator |
| 30 | 0001 1110 | RS | Record separator |
| 31 | 0001 1111 | US | Unit separator |
| 32 | 0010 0000 | SP | Space |
| 33 | 0010 0001 | ! | |
| 34 | 0010 0010 | " | |
| 35 | 0010 0011 | # | |
| 36 | 0010 0100 | $ | |
| 37 | 0010 0101 | % | |
| 38 | 0010 0110 | & | |
| 39 | 0010 0111 | ' | |
| 40 | 0010 1000 | ( | |
| 41 | 0010 1001 | ) | |
| 42 | 0010 1010 | * | |
| 43 | 0010 1011 | + | |
| 44 | 0010 1100 | , | |
| 45 | 0010 1101 | - | |
| 46 | 0010 1110 | . | |
| 47 | 0010 1111 | / | |
| 48 | 0011 0000 | 0 | |
| 49 | 0011 0001 | 1 | |
| 50 | 0011 0010 | 2 | |
| 51 | 0011 0011 | 3 | |
| 52 | 0011 0100 | 4 | |
| 53 | 0011 0101 | 5 | |
| 54 | 0011 0110 | 6 | |
| 55 | 0011 0111 | 7 | |
| 56 | 0011 1000 | 8 | |
| 57 | 0011 1001 | 9 | |
| 58 | 0011 1010 | : | |
| 59 | 0011 1011 | ; | |
| 60 | 0011 1100 | < | |
| 61 | 0011 1101 | = | |
| 62 | 0011 1110 | > | |
| 63 | 0011 1111 | ? | |
| 64 | 0100 0000 | @ | |
| 65 | 0100 0001 | A | |
| 66 | 0100 0010 | B | |
| 67 | 0100 0011 | C | |
| 68 | 0100 0100 | D | |
| 69 | 0100 0101 | E | |
| 70 | 0100 0110 | F | |
| 71 | 0100 0111 | G | |
| 72 | 0100 1000 | H | |
| 73 | 0100 1001 | I | |
| 74 | 0100 1010 | J | |
| 75 | 0100 1011 | K | |
| 76 | 0100 1100 | L | |
| 77 | 0100 1101 | M | |
| 78 | 0100 1110 | N | |
| 79 | 0100 1111 | O | |
| 80 | 0101 0000 | P | |
| 81 | 0101 0001 | Q | |
| 82 | 0101 0010 | R | |
| 83 | 0101 0011 | S | |
| 84 | 0101 0100 | T | |
| 85 | 0101 0101 | U | |
| 86 | 0101 0110 | V | |
| 87 | 0101 0111 | W | |
| 88 | 0101 1000 | X | |
| 89 | 0101 1001 | Y | |
| 90 | 0101 1010 | Z | |
| 91 | 0101 1011 | [ | |
| 92 | 0101 1100 | \ | |
| 93 | 0101 1101 | ] | |
| 94 | 0101 1110 | ^ | |
| 95 | 0101 1111 | _ | |
| 96 | 0110 0000 | ` | |
| 97 | 0110 0001 | a | |
| 98 | 0110 0010 | b | |
| 99 | 0110 0011 | c | |
| 100 | 0110 0100 | d | |
| 101 | 0110 0101 | e | |
| 102 | 0110 0110 | f | |
| 103 | 0110 0111 | g | |
| 104 | 0110 1000 | h | |
| 105 | 0110 1001 | i | |
| 106 | 0110 1010 | j | |
| 107 | 0110 1011 | k | |
| 108 | 0110 1100 | l | |
| 109 | 0110 1101 | m | |
| 110 | 0110 1110 | n | |
| 111 | 0110 1111 | o | |
| 112 | 0111 0000 | p | |
| 113 | 0111 0001 | q | |
| 114 | 0111 0010 | r | |
| 115 | 0111 0011 | s | |
| 116 | 0111 0100 | t | |
| 117 | 0111 0101 | u | |
| 118 | 0111 0110 | v | |
| 119 | 0111 0111 | w | |
| 120 | 0111 1000 | x | |
| 121 | 0111 1001 | y | |
| 122 | 0111 1010 | z | |
| 123 | 0111 1011 | { | |
| 124 | 0111 1100 | | | |
| 125 | 0111 1101 | } | |
| 126 | 0111 1110 | ~ | |
| 127 | 0111 1111 | DEL |
However, ASCII can represent only English text. As computers spread worldwide, EASCII character sets emerged to support more languages. Extending ASCII from 7 bits to 8 allowed 256 distinct characters.
Different regions developed their own EASCII character sets. The first 128 characters remained identical to ASCII, while the remaining 128 varied to meet different languages' needs.
3.4.2 GBK character set¶
Eventually, even EASCII proved too small for many languages. Chinese, for example, has nearly 100,000 characters, with thousands used daily. In 1980, China's National Bureau of Standards released GB2312, containing 6,763 Chinese characters and meeting most basic needs for processing Chinese text.
GB2312 could not handle some rare and traditional characters. GBK extended it to 21,886 Chinese characters. In GBK encoding, ASCII characters use one byte, and Chinese characters use two.
3.4.3 Unicode character set¶
As computing grew, character sets and encoding standards proliferated, creating problems. Most covered only particular languages and did not work well in multilingual settings. Multiple standards also existed for the same language, so exchanging text between computers using different encodings could produce garbled text.
Researchers asked: could a sufficiently comprehensive character set, containing all the world's languages and symbols, solve both multilingual compatibility and garbled-text problems? This idea led to Unicode.
Unicode, whose Chinese name means "unified code", can theoretically accommodate over a million characters. It aims to bring the world's characters into one universal set for processing and displaying different languages, reducing garbled text caused by incompatible standards. Since its release in 1991, it has continued adding languages and characters. As of September 2022, Unicode contained 149,186 characters, including letters, symbols, and emoji.
As a universal character set, Unicode assigns each character a unique code point, or character number, from U+0000 to U+10FFFF. It does not, by itself, specify how these code points are stored in a computer. How can a system parse text containing code points of different lengths? For example, how does it distinguish one two-byte character from two one-byte characters?
One straightforward solution is to store every character in a fixed-width encoding. In Figure 3-7, each character in "Hello" occupies 1 byte, while each in "算法" occupies 2 bytes. Padding the high bits with zeros lets us encode every character in "Hello 算法" with 2 bytes. The system can then read one character every 2 bytes to recover the phrase.
Figure 3-7 Example of Unicode encoding
Description of Figure 3-7: Sixteen-bit view of the code points in Hello算法
Align English and Chinese characters in the same string to 16 bits to compare the convenience and storage cost of fixed-width encoding.
The two columns are headed "Character" and "Unicode", listing the 7-character string Hello算法 (without spaces) from top to bottom. The table below preserves the 16-bit binary values shown in the figure and adds the corresponding hexadecimal code points converted from binary.
In the first five rows, the upper 8 bits of each English character are padded with 00000000 in gray, while the lower 8 bits retain the original code point. The brace on the right reads "One-byte English characters (high bits padded with 0)", and the brace beside the last two rows, "算" and "法", reads "Two-byte Chinese characters".
| Position and character | 16-bit binary in figure | Hexadecimal code point (added) |
|---|---|---|
| 1: H | 00000000 01001000 | U+0048 |
| 2: e | 00000000 01100101 | U+0065 |
| 3: l | 00000000 01101100 | U+006C |
| 4: l | 00000000 01101100 | U+006C |
| 5: o | 00000000 01101111 | U+006F |
| 6: 算 | 01111011 10010111 | U+7B97 |
| 7: 法 | 01101100 11010101 | U+6CD5 |
If 1-byte English code points and 2-byte Chinese code points were mixed directly without padding, two consecutive bytes could be misparsed either as a single Chinese character or as two English letters. Zero-padding in the figure makes every character in this example occupy 2 bytes so the stream can be sliced at fixed intervals, at the cost of using twice as much space as ASCII for the five English letters.
This diagram only illustrates 16-bit values for characters within the Basic Multilingual Plane (BMP). Unicode itself defines code points up to U+10FFFF, which require 21 bits; the actual byte length depends on the encoding scheme such as UTF-8 or UTF-16, and not all Unicode characters occupy a fixed 2 bytes.
ASCII has already shown that English text needs only 1 byte per character. This scheme would double its storage compared with ASCII, wasting memory. We therefore need a more efficient Unicode encoding.
3.4.4 UTF-8 encoding¶
UTF-8 is now the most widely used Unicode encoding worldwide. It is variable-length, using 1 to 4 bytes per character depending on the character. ASCII characters need 1 byte, Latin and Greek letters need 2, common Chinese characters need 3, and some less common characters need 4.
UTF-8's rules have two cases.
- For a one-byte character, set the highest bit to \(0\) and the remaining 7 bits to its Unicode code point. ASCII occupies the first 128 Unicode code points, so UTF-8 is backward-compatible with ASCII. UTF-8 can therefore decode old ASCII text.
- For an \(n\)-byte character, where \(n > 1\), set the first byte's leading \(n\) bits to \(1\) and the next bit, \(n + 1\), to \(0\). Starting with the second byte, set the leading 2 bits of every byte to \(10\). Fill the remaining bits with the character's Unicode code point.
Figure 3-8 shows UTF-8 for "Hello算法". Since the leading \(n\) bits are \(1\), the system can determine the character length \(n\) by counting the leading \(1\) bits.
Why do all remaining bytes begin with \(10\)? This \(10\) acts as a check marker. If decoding starts at the wrong byte, the leading \(10\) helps the system quickly detect the problem.
The prefix \(10\) works as a marker because no character's first byte can begin with \(10\) under UTF-8's rules. To see this by contradiction, suppose it did begin with \(10\). The single leading one would imply a length of \(1\) byte, corresponding to ASCII, but an ASCII byte must begin with \(0\), a contradiction.
Figure 3-8 Example of UTF-8 encoding
Description of Figure 3-8: UTF-8 encoding of Hello算法
Compare single-byte and three-byte encodings across seven characters, identifying leading bytes and continuation bytes.
The input string is Hello算法 without spaces. The figure writes the code points of these 7 characters in 16 bits because all of them fall within U+FFFF; the full Unicode code point range extends up to U+10FFFF and requires 21 bits, so this example should not be generalized to mean that every code point fits in 16 bits.
| Position and character | Unicode code point (from binary) | 16-bit code point in figure | UTF-8 binary bytes | Byte count |
|---|---|---|---|---|
| 1: H | U+0048 | 00000000 01001000 | 01001000 | 1 |
| 2: e | U+0065 | 00000000 01100101 | 01100101 | 1 |
| 3: l | U+006C | 00000000 01101100 | 01101100 | 1 |
| 4: l | U+006C | 00000000 01101100 | 01101100 | 1 |
| 5: o | U+006F | 00000000 01101111 | 01101111 | 1 |
| 6: 算 | U+7B97 | 01111011 10010111 | 11100111 10101110 10010111 | 3 |
| 7: 法 | U+6CD5 | 01101100 11010101 | 11100110 10110011 10010101 | 3 |
Each English character uses the single-byte template 0xxxxxxx, placing its code point in the lower 7 bits. Both "算" and "法" use the three-byte template 1110xxxx 10xxxxxx 10xxxxxx: the leading byte starts with prefix 1110, where the 0 after the three 1s is also part of the prefix, and each of the two continuation bytes starts with 10. The remaining 4 + 6 + 6 payload bits hold the code point in order: "算" splits into 0111, 101110, and 010111, while "法" splits into 0110, 110011, and 010101.
These bit prefixes distinguish single-byte characters, multi-byte leading bytes, and continuation bytes. In this example, the five English characters take 1 byte each and the two Chinese characters take 3 bytes each, for a total of 5 × 1 + 2 × 3 = 11 bytes.
Two other common encodings are:
- UTF-16: Uses 2 or 4 bytes per character. ASCII and common non-English characters use 2 bytes; some characters require 4. For a two-byte character, its UTF-16 encoding equals its Unicode code point.
- UTF-32: Uses 4 bytes for every character. It therefore takes more space than UTF-8 or UTF-16, especially for text containing mostly ASCII characters.
In terms of storage, UTF-8 is efficient for English characters because each uses only 1 byte. UTF-16 is more efficient for some non-English characters, such as Chinese, using 2 bytes where UTF-8 may require 3.
In terms of compatibility, UTF-8 is the most widely supported, and many tools and libraries prioritize it.
3.4.5 Character encoding in programming languages¶
Historically, most programming languages have stored strings at runtime using fixed-width encodings such as UTF-16 or UTF-32. Fixed-width encoding lets us treat a string as an array, with the following advantages.
- Random access: UTF-16 strings support straightforward random access. With variable-length UTF-8, finding the \(i\)-th character requires traversing from the beginning to the \(i\)-th character, taking \(O(n)\) time.
- Character counting: Similarly, finding the length of a UTF-16 string is an \(O(1)\) operation, while finding the character count of a UTF-8 string requires traversing the whole string.
- String operations: Operations such as splitting, concatenation, insertion, and deletion are easier on UTF-16 strings. With UTF-8, they usually require extra work to avoid producing invalid encodings.
The design of string representations is an interesting subject involving many factors.
- Java's
Stringuses UTF-16, with 2 bytes per character. When Java was designed, 16 bits were thought sufficient for every character. This turned out to be incorrect: Unicode later expanded beyond 16 bits, so a Java character may now require a pair of 16-bit values called a surrogate pair. - JavaScript and TypeScript use UTF-16 for similar historical reasons. When Netscape introduced JavaScript in 1995, Unicode was still young, and 16 bits could represent all its characters at the time.
- C# uses UTF-16 largely because Microsoft designed .NET, and many Microsoft technologies, including Windows, use UTF-16 extensively.
Having underestimated the number of characters, these languages had to adopt surrogate pairs for Unicode characters beyond 16 bits. This was a compromise. A character in such a string may occupy 2 or 4 bytes, losing the benefit of fixed width, and handling surrogate pairs requires additional code, making programming and debugging more complex.
For these reasons, some languages use different representations.
- Python's
struses Unicode with a flexible representation whose character width depends on the largest code point in the string. If all characters are ASCII, each uses 1 byte. If some exceed ASCII but all lie within the Basic Multilingual Plane (BMP), each uses 2 bytes. If any lie outside the BMP, each uses 4 bytes. - Go's
stringuses UTF-8 internally. Go also providesruneto represent a single Unicode code point. - Rust's
strandStringuse UTF-8 internally, whilecharrepresents a single Unicode code point.
These descriptions concern string storage within programming languages. How strings are stored in files or transmitted over a network is a separate question. For file storage and network transmission, strings are usually encoded as UTF-8 for compatibility and space efficiency.