Character Encoding: ASCII, Unicode and UTF-8
Understand how text becomes bytes, why accents and emoji break, and how to keep UTF-8 consistent from file to database.
Key takeaways
- Unicode assigns each character a number called a code point; an encoding turns code points into bytes.
- ASCII covers 128 characters, and UTF-8 stores those same characters as the same single bytes.
- UTF-8 uses one to four bytes per code point, so character count and byte count often differ.
- Text carries no reliable label of its own, so every file, response and database must agree on the encoding.
- What a reader sees as one character may be several code points, which affects length, searching and cutting strings.
A computer stores text as numbers. A character set decides which number stands for which character, and an encoding decides how that number is written as bytes. Unicode is the character set that covers the world's writing systems, and UTF-8 is the encoding you should use for nearly everything.
Garbled text, such as café where café should be, almost always means bytes were written with one encoding and read with another. Once you can see that, these bugs become straightforward to track down.
Bytes need an agreement
A byte is a number from 0 to 255. Nothing in the byte 233 says it means é. In one old Western European code page it does; in a Cyrillic code page the same byte is a different letter; on its own in UTF-8 it isn't valid at all.
An encoding is the agreement. If the writer and reader don't share it, the bytes arrive intact and the meaning is lost. This is why bytes alone are never enough to define text.
ASCII and the code page years
ASCII, the American Standard Code for Information Interchange, uses 7 bits and defines 128 codes: English letters in both cases, digits, punctuation and control codes such as tab and line feed. A is 65, a is 97 and the digit 0 is 48.
It has no accented letters, no Greek, no Chinese. Because computers used 8-bit bytes, vendors and standards bodies filled the other 128 values in many incompatible ways: the ISO 8859 series, various Windows code pages and others. Some East Asian languages needed multi-byte schemes of their own. A document could be read correctly only if you knew which one had been used, and mixing languages in one file was difficult or impossible.
Unicode: one number per character
Unicode replaces the patchwork with a single catalog. Each entry has a code point, written as U+ and a hexadecimal number.
| Character | Code point | UTF-8 bytes (hex) |
|---|---|---|
| A | U+0041 | 41 |
| é | U+00E9 | C3 A9 |
| € | U+20AC | E2 82 AC |
| 😀 | U+1F600 | F0 9F 98 80 |
The code space runs from U+0000 to U+10FFFF. New characters, including emoji, are added in new versions of the standard, which is why an older device can show an empty box for a recent symbol: the text is fine, but no installed font or software knows how to draw it.
How UTF-8 packs code points
UTF-8, defined in RFC 3629, uses a variable number of bytes. The first byte shows how many follow, and continuation bytes always start with the bits 10.
Basis: RFC 3629 UTF-8 encoding ranges.
The design has practical advantages. Any pure ASCII file is already valid UTF-8. A reader that starts in the middle of a stream can find the next character boundary. And there's no byte order to worry about, because the unit is a single byte.
UTF-16 and UTF-32
UTF-16 uses two bytes for most common characters and four, called a surrogate pair, for those above U+FFFF. Windows interfaces, Java and JavaScript use it internally. That's why a single emoji reports a length of 2 in JavaScript:
"é".length // 1
"😀".length // 2
[..."😀"].length // 1 UTF-32 uses four bytes for every code point. It's simple and bulky. Both UTF-16 and UTF-32 come in big and little endian orders, which a byte order mark at the start of a file can indicate. UTF-8 doesn't need one, though some programs add it, and others stumble over it.
One visible character, several code points
Unicode lets some characters be built from parts. é can be the single code point U+00E9, or the letter e followed by the combining accent U+0301. They look identical and compare as different.
Normalization converts text to a consistent form. NFC prefers combined characters; NFD splits them. Normalize before comparing or searching text from different sources.
Emoji go further: flags, skin tone variants and family groups can be sequences of several code points joined together. What a person perceives as one character is called a grapheme cluster. Cutting a string at a byte or code unit count can slice one in half, so truncate with a library that understands these boundaries.
Recognizing common damage
| Symptom | Likely cause |
|---|---|
é instead of é | UTF-8 bytes read as a single-byte Western code page |
� replacement character | Bytes that aren't valid in the encoding used to read |
? where letters were | Converted to a set that lacks them; the original is lost |
| Empty boxes | Missing font or unsupported new character |
| Odd marks at file start | A byte order mark shown as text |
Doubled garble like é | The same mistake applied twice |
A question mark that was saved to disk can't be reversed. The first two can often be fixed by rereading the original bytes correctly.
Setting UTF-8 everywhere
Consistency across every layer is what prevents trouble.
- Files: set your editor to save UTF-8.
- HTML: put
<meta charset="utf-8">early in thehead. - HTTP: send
Content-Type: text/html; charset=utf-8, part of the headers described in HTTP requests and responses. - Databases: use a UTF-8 character set for tables and connections. In MySQL and MariaDB, choose
utf8mb4; the olderutf8name there has meant a three-byte subset that can't store emoji. - Code: name the encoding when opening files, such as
open(path, encoding="utf-8")in Python. - Terminals and scripts: Windows PowerShell 5.1 has different defaults for different cmdlets, so pass
-Encodingexplicitly.
JSON passed between systems is expected to be UTF-8, as noted in JSON explained, and CSV files are a frequent source of mismatches.
A worked repair
Say a customer list shows Zoë as Zoë. Work backward through the path the text took.
First, find the earliest copy. Open the original file in an editor that lets you choose the encoding and shows which one it picked. If the name is correct when read as UTF-8, the file is fine and a later step misread it.
Next, check each hop: the import tool's encoding setting, the database connection's character set, the column's character set, and the header on the page that displays the result. Change one setting at a time and test with a short string containing an accented letter, a euro sign and an emoji. The three need two, three and four bytes in UTF-8, so they expose different faults.
If the damaged form is what's stored, a conversion can sometimes reverse it, by encoding the text with the wrong code page and decoding the result as UTF-8. Only try this on a copy. A table that holds a mix of correct and damaged rows will be harmed by a blanket conversion, so select the affected rows carefully and compare before replacing anything.
Length, sorting and comparison
Because bytes, code points and visible characters differ, decide which one a limit means. A database column or protocol field may count bytes, while a form tells the user "50 characters". Test limits with non-English text so that a name isn't cut in the middle of a byte sequence.
Sorting and case rules also depend on language. Ordering by raw code point puts Z before a and places accented letters after the whole basic alphabet, which readers find strange. Unicode defines a collation algorithm, with adjustments for each language, and databases and programming languages offer locale-aware comparison. Uppercasing isn't universal either: Turkish distinguishes dotted and dotless i, and the German sharp s can become two letters.
For identifiers such as usernames, choose strict rules. Normalize, compare in a consistent case-folded form and consider limiting the allowed scripts, while keeping people's actual names free to use their own letters.
Look-alikes and safety
Different scripts contain characters that look nearly identical, such as Latin a and Cyrillic а. This matters for web addresses and usernames, and internationalized domain names explains how browsers respond. Invisible characters, including zero-width spaces and direction controls, can also hide inside copied text and break matching or mislead a reader.
When a string behaves strangely, inspect it code point by code point with a Unicode text inspector. On Linux or macOS, xxd file.txt shows the raw bytes; in PowerShell, Format-Hex does the same.
Fonts are a separate layer
Correct bytes don't guarantee a correct picture. A font supplies the shapes, and no single font covers every script. Operating systems and browsers fall back to other installed fonts when one lacks a character, which is why a line of mixed text can change style partway through. If only some readers see boxes, check their fonts before suspecting your encoding.
Common questions
Is UTF-8 the same as Unicode?
No. Unicode is the catalog of characters and their rules. UTF-8 is one way of writing those numbers as bytes.
Can a program detect an encoding automatically?
It can guess. Valid UTF-8 is fairly easy to recognize, but single-byte code pages look alike to software. Declaring the encoding is far more reliable than guessing.