<inputclass="md-option"data-md-color-media=""data-md-color-scheme="default"data-md-color-primary="white"data-md-color-accent="indigo"aria-label="Switch to dark mode"type="radio"name="__palette"id="__palette_0">
<labelclass="md-header__button md-icon"title="Switch to dark mode"for="__palette_1"hidden>
<inputclass="md-option"data-md-color-media=""data-md-color-scheme="slate"data-md-color-primary="grey"data-md-color-accent="indigo"aria-label="Switch to light mode"type="radio"name="__palette"id="__palette_1">
<labelclass="md-header__button md-icon"title="Switch to light mode"for="__palette_0"hidden>
<h1id="34-character-encoding">3.4 Character Encoding *<aclass="headerlink"href="#34-character-encoding"title="Permanent link">¶</a></h1>
<p>In computers, all data is stored in binary form, and the character <code>char</code> is no exception. To represent characters, we need to establish a "character set" that defines a one-to-one correspondence between each character and binary numbers. With a character set, computers can convert binary numbers to characters by looking up a table.</p>
<h2id="341-ascii-character-set">3.4.1 ASCII Character Set<aclass="headerlink"href="#341-ascii-character-set"title="Permanent link">¶</a></h2>
<p>The "ASCII code" is one of the earliest character sets, officially known as the American Standard Code for Information Interchange. It uses 7 binary digits (the lower 7 bits of a byte) to represent a character, allowing for a maximum of 128 different characters. As shown in the Figure 3-6 , ASCII includes uppercase and lowercase English letters, numbers 0 ~ 9, some punctuation marks, and some control characters (such as newline and tab).</p>
<p>However, <strong>ASCII can only represent English characters</strong>. With the globalization of computers, a character set called "EASCII" was developed to represent more languages. It expands on the 7-bit basis of ASCII to 8 bits, enabling the representation of 256 different characters.</p>
<p>Globally, a series of EASCII character sets for different regions emerged. The first 128 characters of these sets are uniformly ASCII, while the remaining 128 characters are defined differently to cater to various language requirements.</p>
<h2id="342-gbk-character-set">3.4.2 GBK Character Set<aclass="headerlink"href="#342-gbk-character-set"title="Permanent link">¶</a></h2>
<p>Later, it was found that <strong>EASCII still could not meet the character requirements of many languages</strong>. For instance, there are nearly a hundred thousand Chinese characters, with several thousand used in everyday life. In 1980, China's National Standards Bureau released the "GB2312" character set, which included 6763 Chinese characters, essentially meeting the computer processing needs for Chinese.</p>
<p>However, GB2312 could not handle some rare and traditional characters. The "GBK" character set, an expansion of GB2312, includes a total of 21886 Chinese characters. In the GBK encoding scheme, ASCII characters are represented with one byte, while Chinese characters use two bytes.</p>
<h2id="343-unicode-character-set">3.4.3 Unicode Character Set<aclass="headerlink"href="#343-unicode-character-set"title="Permanent link">¶</a></h2>
<p>With the rapid development of computer technology and a plethora of character sets and encoding standards, numerous problems arose. On one hand, these character sets generally only defined characters for specific languages and could not function properly in multilingual environments. On the other hand, the existence of multiple character set standards for the same language caused garbled text when information was exchanged between computers using different encoding standards.</p>
<p>Researchers of that era thought: <strong>What if we introduced a comprehensive character set that included all languages and symbols worldwide, wouldn't that solve the problems of cross-language environments and garbled text?</strong> Driven by this idea, the extensive character set, Unicode, was born.</p>
<p>The Chinese name for "Unicode" is "统一码" (Unified Code), theoretically capable of accommodating over a million characters. It aims to incorporate characters from all over the world into a single set, providing a universal character set for processing and displaying various languages and reducing the issues of garbled text due to different encoding standards.</p>
<p>Since its release in 1991, Unicode has continually expanded to include new languages and characters. As of September 2022, Unicode contains 149,186 characters, including characters, symbols, and even emojis from various languages. In the vast Unicode character set, commonly used characters occupy 2 bytes, while some rare characters take up 3 or even 4 bytes.</p>
<p>Unicode is a universal character set that assigns a number (called a "code point") to each character, <strong>but it does not specify how these character code points should be stored in a computer</strong>. One might ask: When Unicode code points of varying lengths appear in a text, how does the system parse the characters? For example, given a 2-byte code, how does the system determine if it represents a single 2-byte character or two 1-byte characters?</p>
<p>A straightforward solution to this problem is to store all characters as equal-length encodings. As shown in the Figure 3-7 , each character in "Hello" occupies 1 byte, while each character in "算法" (algorithm) occupies 2 bytes. We could encode all characters in "Hello 算法" as 2 bytes by padding the higher bits with zeros. This way, the system can parse a character every 2 bytes, recovering the content of the phrase.</p>
<palign="center"> Figure 3-7 Unicode Encoding Example </p>
<p>However, as ASCII has shown us, encoding English only requires 1 byte. Using the above approach would double the space occupied by English text compared to ASCII encoding, which is a waste of memory space. Therefore, a more efficient Unicode encoding method is needed.</p>
<p>Currently, UTF-8 has become the most widely used Unicode encoding method internationally. <strong>It is a variable-length encoding</strong>, using 1 to 4 bytes to represent a character, depending on the complexity of the character. ASCII characters need only 1 byte, Latin and Greek letters require 2 bytes, commonly used Chinese characters need 3 bytes, and some other rare characters need 4 bytes.</p>
<p>The encoding rules for UTF-8 are not complex and can be divided into two cases:</p>
<ul>
<li>For 1-byte characters, set the highest bit to <spanclass="arithmatex">\(0\)</span>, and the remaining 7 bits to the Unicode code point. Notably, ASCII characters occupy the first 128 code points in the Unicode set. This means that <strong>UTF-8 encoding is backward compatible with ASCII</strong>. This implies that UTF-8 can be used to parse ancient ASCII text.</li>
<li>For characters of length <spanclass="arithmatex">\(n\)</span> bytes (where <spanclass="arithmatex">\(n > 1\)</span>), set the highest <spanclass="arithmatex">\(n\)</span> bits of the first byte to <spanclass="arithmatex">\(1\)</span>, and the <spanclass="arithmatex">\((n + 1)^{\text{th}}\)</span> bit to <spanclass="arithmatex">\(0\)</span>; starting from the second byte, set the highest 2 bits of each byte to <spanclass="arithmatex">\(10\)</span>; the rest of the bits are used to fill the Unicode code point.</li>
</ul>
<p>The Figure 3-8 shows the UTF-8 encoding for "Hello算法". It can be observed that since the highest <spanclass="arithmatex">\(n\)</span> bits are set to <spanclass="arithmatex">\(1\)</span>, the system can determine the length of the character as <spanclass="arithmatex">\(n\)</span> by counting the number of highest bits set to <spanclass="arithmatex">\(1\)</span>.</p>
<p>But why set the highest 2 bits of the remaining bytes to <spanclass="arithmatex">\(10\)</span>? Actually, this <spanclass="arithmatex">\(10\)</span> serves as a kind of checksum. If the system starts parsing text from an incorrect byte, the <spanclass="arithmatex">\(10\)</span> at the beginning of the byte can help the system quickly detect an anomaly.</p>
<p>The reason for using <spanclass="arithmatex">\(10\)</span> as a checksum is that, under UTF-8 encoding rules, it's impossible for the highest two bits of a character to be <spanclass="arithmatex">\(10\)</span>. This can be proven by contradiction: If the highest two bits of a character are <spanclass="arithmatex">\(10\)</span>, it indicates that the character's length is <spanclass="arithmatex">\(1\)</span>, corresponding to ASCII. However, the highest bit of an ASCII character should be <spanclass="arithmatex">\(0\)</span>, contradicting the assumption.</p>
<palign="center"> Figure 3-8 UTF-8 Encoding Example </p>
<p>Apart from UTF-8, other common encoding methods include:</p>
<ul>
<li><strong>UTF-16 Encoding</strong>: Uses 2 or 4 bytes to represent a character. All ASCII characters and commonly used non-English characters are represented with 2 bytes; a few characters require 4 bytes. For 2-byte characters, the UTF-16 encoding is equal to the Unicode code point.</li>
<li><strong>UTF-32 Encoding</strong>: Every character uses 4 bytes. This means UTF-32 occupies more space than UTF-8 and UTF-16, especially for texts with a high proportion of ASCII characters.</li>
</ul>
<p>From the perspective of storage space, UTF-8 is highly efficient for representing English characters, requiring only 1 byte; UTF-16 might be more efficient for encoding some non-English characters (like Chinese), as it requires only 2 bytes, while UTF-8 might need 3 bytes.</p>
<p>From a compatibility standpoint, UTF-8 is the most versatile, with many tools and libraries supporting UTF-8 as a priority.</p>
<h2id="345-character-encoding-in-programming-languages">3.4.5 Character Encoding in Programming Languages<aclass="headerlink"href="#345-character-encoding-in-programming-languages"title="Permanent link">¶</a></h2>
<p>In many classic programming languages, strings during program execution are encoded using fixed-length encodings like UTF-16 or UTF-32. This allows strings to be treated as arrays, offering several advantages:</p>
<ul>
<li><strong>Random Access</strong>: Strings encoded in UTF-16 can be accessed randomly with ease. For UTF-8, which is a variable-length encoding, locating the <spanclass="arithmatex">\(i^{th}\)</span> character requires traversing the string from the start to the <spanclass="arithmatex">\(i^{th}\)</span> position, taking <spanclass="arithmatex">\(O(n)\)</span> time.</li>
<li><strong>Character Counting</strong>: Similar to random access, counting the number of characters in a UTF-16 encoded string is an <spanclass="arithmatex">\(O(1)\)</span> operation. However, counting characters in a UTF-8 encoded string requires traversing the entire string.</li>
<li><strong>String Operations</strong>: Many string operations like splitting, concatenating, inserting, and deleting are easier on UTF-16 encoded strings. These operations generally require additional computation on UTF-8 encoded strings to ensure the validity of the UTF-8 encoding.</li>
</ul>
<p>The design of character encoding schemes in programming languages is an interesting topic involving various factors:</p>
<ul>
<li>Java’s <code>String</code> type uses UTF-16 encoding, with each character occupying 2 bytes. This was based on the initial belief that 16 bits were sufficient to represent all possible characters, a judgment later proven incorrect. As the Unicode standard expanded beyond 16 bits, characters in Java may now be represented by a pair of 16-bit values, known as “surrogate pairs.”</li>
<li>JavaScript and TypeScript use UTF-16 encoding for similar reasons as Java. When JavaScript was first introduced by Netscape in 1995, Unicode was still in its early stages, and 16-bit encoding was sufficient to represent all Unicode characters.</li>
<li>C# uses UTF-16 encoding, largely because the .NET platform, designed by Microsoft, and many Microsoft technologies, including the Windows operating system, extensively use UTF-16 encoding.</li>
</ul>
<p>Due to the underestimation of character counts, these languages had to resort to using "surrogate pairs" to represent Unicode characters exceeding 16 bits. This approach has its drawbacks: strings containing surrogate pairs may have characters occupying 2 or 4 bytes, losing the advantage of fixed-length encoding, and handling surrogate pairs adds to the complexity and debugging difficulty of programming.</p>
<p>Owing to these reasons, some programming languages have adopted different encoding schemes:</p>
<ul>
<li>Python’s <code>str</code> type uses Unicode encoding with a flexible representation where the storage length of characters depends on the largest Unicode code point in the string. If all characters are ASCII, each character occupies 1 byte; if characters exceed ASCII but are within the Basic Multilingual Plane (BMP), each occupies 2 bytes; if characters exceed the BMP, each occupies 4 bytes.</li>
<li>Go’s <code>string</code> type internally uses UTF-8 encoding. Go also provides the <code>rune</code> type for representing individual Unicode code points.</li>
<li>Rust’s <code>str</code> and <code>String</code> types use UTF-8 encoding internally. Rust also offers the <code>char</code> type for individual Unicode code points.</li>
</ul>
<p>It’s important to note that the above discussion pertains to how strings are stored in programming languages, <strong>which is a different issue from how strings are stored in files or transmitted over networks</strong>. For file storage or network transmission, strings are usually encoded in UTF-8 format for optimal compatibility and space efficiency.</p>
<scriptid="__config"type="application/json">{"base":"../..","features":["content.action.edit","content.code.annotate","content.code.copy","content.tabs.link","content.tooltips","navigation.indexes","navigation.top","navigation.footer","navigation.tracking","search.highlight","search.share","search.suggest","toc.follow"],"search":"../../assets/javascripts/workers/search.f886a092.min.js","translations":{"clipboard.copied":"Copied to clipboard","clipboard.copy":"Copy to clipboard","search.result.more.one":"1 more on this page","search.result.more.other":"# more on this page","search.result.none":"No matching documents","search.result.one":"1 matching document","search.result.other":"# matching documents","search.result.placeholder":"Type to start searching","search.result.term.missing":"Missing","select.version":"Select version"}}</script>