How letters are stored

Every letter is a number · Part of Complexity and data

Key idea

Practice

6 questions · about 3 min

Explained step by step

Character set

The computer only stores numbers in binary, so storing letters needs a table that gives each character a number. That table is a character set. For example, in ASCII "A" is 65 and "a" is 97. To show a text, the computer reads the numbers and looks up in the table which letter each one is. If 2 computers use different tables, the same number is read as another letter and garbled text appears.

ASCII

ASCII was the first character set. It uses 7 bits per character, so it has room for 2⁷ = 128: English letters in upper and lower case, the digits 0 to 9, punctuation marks and control characters like the line break. But it only works for English: it has no "ñ" or accents. That's why 8-bit extended versions appeared, with 256 slots, using the 128 extra for other languages, but each region made its own.

Unicode

With so many different sets, multilingual texts kept breaking. Unicode solved it with a single set for every language and symbol in the world: it has room for over 1 million characters. It gives each one a unique number called a code point, written like U+0041 for "A". But Unicode only says which number each character has, not how many bytes it takes when stored: that's decided by the encoding, like UTF-8.

UTF-8

If every Unicode character always took 4 bytes, an English text would take 4 times as much as in ASCII. UTF-8 solves that with variable length: it uses 1 to 4 bytes depending on the character. ASCII letters take 1 byte, "ñ" or accented letters 2, most Chinese characters 3, and emojis 4. Also, any old ASCII text is already valid UTF-8. That's why it's the most used encoding in the world.

UTF-8 has 2 rules. If the character takes 1 byte, that byte starts with 0 and the rest is the code point, just like ASCII. If it takes n bytes, the first starts with n ones followed by a 0, and each following byte starts with 10. So, when reading the first byte, the computer counts the leading 1s and knows how many bytes make up the character. And since no character starts with 10, if it starts reading in the middle of one, it notices right away.

There are 2 other common Unicode encodings. UTF-16 uses 2 or 4 bytes, and most usual characters fit in 2. UTF-32 always uses 4. With a fixed length, going to character 500 is a calculation, O(1); in UTF-8, since each character has a different size, you have to walk from the start, O(n). That's why Java, JavaScript and C# use UTF-16 internally, and Go and Rust use UTF-8. For files and for sending text over the network, UTF-8 is almost always used.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Every letter is a number