Skip to content

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.

Complete ASCII code table (matching every row in the figure)
DecimalBinaryCharacterMeaning (shown in figure)
00000 0000NULNull
10000 0001SOHStart of heading
20000 0010STXStart of text
30000 0011ETXEnd of text
40000 0100EOTEnd of transmission
50000 0101ENQEnquiry
60000 0110ACKAcknowledge
70000 0111BELBell
80000 1000BSBackspace
90000 1001HTHorizontal tab
100000 1010LFLine feed
110000 1011VTVertical tab
120000 1100FFForm feed
130000 1101CRCarriage return
140000 1110SOShift out
150000 1111SIShift in
160001 0000DLEData link escape
170001 0001DC1Device control 1
180001 0010DC2Device control 2
190001 0011DC3Device control 3
200001 0100DC4Device control 4
210001 0101NAKNegative acknowledge
220001 0110SYNSynchronous idle
230001 0111ETBEnd of transmission block
240001 1000CANCancel
250001 1001EMEnd of medium
260001 1010SUBSubstitute
270001 1011ESCEscape
280001 1100FSFile separator
290001 1101GSGroup separator
300001 1110RSRecord separator
310001 1111USUnit separator
320010 0000SPSpace
330010 0001!
340010 0010"
350010 0011#
360010 0100$
370010 0101%
380010 0110&
390010 0111'
400010 1000(
410010 1001)
420010 1010*
430010 1011+
440010 1100,
450010 1101-
460010 1110.
470010 1111/
480011 00000
490011 00011
500011 00102
510011 00113
520011 01004
530011 01015
540011 01106
550011 01117
560011 10008
570011 10019
580011 1010:
590011 1011;
600011 1100<
610011 1101=
620011 1110>
630011 1111?
640100 0000@
650100 0001A
660100 0010B
670100 0011C
680100 0100D
690100 0101E
700100 0110F
710100 0111G
720100 1000H
730100 1001I
740100 1010J
750100 1011K
760100 1100L
770100 1101M
780100 1110N
790100 1111O
800101 0000P
810101 0001Q
820101 0010R
830101 0011S
840101 0100T
850101 0101U
860101 0110V
870101 0111W
880101 1000X
890101 1001Y
900101 1010Z
910101 1011[
920101 1100\
930101 1101]
940101 1110^
950101 1111_
960110 0000`
970110 0001a
980110 0010b
990110 0011c
1000110 0100d
1010110 0101e
1020110 0110f
1030110 0111g
1040110 1000h
1050110 1001i
1060110 1010j
1070110 1011k
1080110 1100l
1090110 1101m
1100110 1110n
1110110 1111o
1120111 0000p
1130111 0001q
1140111 0010r
1150111 0011s
1160111 0100t
1170111 0101u
1180111 0110v
1190111 0111w
1200111 1000x
1210111 1001y
1220111 1010z
1230111 1011{
1240111 1100|
1250111 1101}
1260111 1110~
1270111 1111DEL

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".

Per-character code points of Hello算法
Position and character16-bit binary in figureHexadecimal code point (added)
1: H00000000 01001000U+0048
2: e00000000 01100101U+0065
3: l00000000 01101100U+006C
4: l00000000 01101100U+006C
5: o00000000 01101111U+006F
6: 算01111011 10010111U+7B97
7: 法01101100 11010101U+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.

Per-character code points and UTF-8 bytes
Position and characterUnicode code point (from binary)16-bit code point in figureUTF-8 binary bytesByte count
1: HU+004800000000 01001000010010001
2: eU+006500000000 01100101011001011
3: lU+006C00000000 01101100011011001
4: lU+006C00000000 01101100011011001
5: oU+006F00000000 01101111011011111
6: 算U+7B9701111011 1001011111100111 10101110 100101113
7: 法U+6CD501101100 1101010111100110 10110011 100101013

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 String uses 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 str uses 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 string uses UTF-8 internally. Go also provides rune to represent a single Unicode code point.
  • Rust's str and String use UTF-8 internally, while char represents 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.

Share your insights, questions, or suggestions in the comments