How characters are represented -- ASCII and Unicode
In this lecture you will understand: how text is represented in a computer that can only store numbers, and why a file sometimes shows garbled text when opened.
A real-life analogy: room numbers
Imagine a building with 128 rooms.
The front desk does not manage rooms with names like 'presidential suite' or 'garden room'.
They assign each room a number: 101, 102, 103...
Look up number 101 and you know: oh, that is a standard king room.
Computers handle text with exactly the same idea:
Assign each character a numeric code, then store and process that number.
This 'numbering scheme' is character encoding.
ASCII: the starting point of all encodings
ASCII (American Standard Code for Information Interchange) was born in 1963.
It uses 7 bits to represent one character, so it can represent 2^7 = 128 characters in total.
Contains:
- Control characters (0~31): invisible characters such as carriage return, line feed, backspace
- Printable characters (32~126): space, punctuation, digits 0-9, uppercase A-Z, lowercase a-z
- DEL delete character (127)
Full ASCII table (0~127)

Several key landmarks of ASCII
| Character category | ASCII range | Features |
|---|---|---|
| '0' ~ '9' | 48 ~ 57 (0x30 ~ 0x39) | The code for digit 0 is 48, not 0 |
| 'A' ~ 'Z' | 65 ~ 90 (0x41 ~ 0x5A) | Uppercase letters are arranged consecutively |
| 'a' ~ 'z' | 97 ~ 122 (0x61 ~ 0x7A) | Lowercase letters are arranged consecutively |
| Line feed '\n' | 10 (0x0A) | LF, Unix/Mac line break |
| Carriage return '\r' | 13 (0x0D) | CR, old Mac line break |
The clever relationship between uppercase and lowercase
Notice the binary representations of uppercase 'A' (65) and lowercase 'a' (97):
'A' = 01
0
00001
'a' = 01
1
00001
Only bit 5 differs (value = 32, bits numbered from right to left, starting at 0)
This is no coincidence.
At the binary level, changing bit 5 from 0 to 1 directly converts uppercase to lowercase.
This ingenious design let early teleprinters switch case mode with just a simple circuit.
Bit 5 is counted using bits numbered from right to left starting at 0 (i.e. the LSB is bit 0), which is the most common bit-numbering convention in computing:

Uppercase and lowercase letters differ by 32, so at the ASCII level,
'a' - 'A' = 32,'A' | 0x20 = 'a'(bit operations switch case). All of this stems from the ingenious layout of the ASCII table.
The limitation of ASCII: one byte is not enough
ASCII has only 128 characters, which is enough for English.
But when computers spread to Europe, a problem appeared:
French has e, German has u, Spanish has n -- these letters with accent marks simply do not exist in ASCII.
So each country began 'patching' -- using the 128~255 range that ASCII left unused (setting the 8th bit to 1):
- Western Europe: ISO-8859-1 (Latin-1), added Western European characters like e, u
- Eastern Europe: ISO-8859-2, added Cyrillic letters
- Greece: ISO-8859-7, added Greek letters
- China: GB2312/GBK, uses two bytes to represent one Chinese character
- Japan: Shift-JIS
- Korea: EUC-KR
This became a disaster -- the same binary data is interpreted as completely different text under different encodings.
You open a Japanese document and see garbled text? That is the classic symptom of an encoding mismatch.
Unicode: give every character in the world a unique number
Unicode's goal is simple yet grand:
Assign a unique numeric code (code point) to every character in the world.
Unicode is not 16-bit -- its code point range is U+0000 to U+10FFFF, able to hold over 1 million characters.
About 150,000 characters have been assigned so far, covering almost all of the world's writing systems, as well as emoji.
Unicode code point examples
| Character | Unicode code point | Meaning | Block |
|---|---|---|---|
| A | U+0041 | Latin capital letter A | Basic Latin (ASCII compatible) |
| 'Ni' (a Chinese character) | U+4F60 | CJK Chinese character 'Ni' | CJK Unified Ideographs |
| Good | U+597D | CJK Chinese character 'Hao' | CJK Unified Ideographs |
| hello | U+68D2 | Arabic 'Ni Hao' (hello) | Arabic |
| runoob | U+E0001 | Language tag | Tags block |
Note: Unicode is only a 'numbering scheme' -- it tells you 'character X has code U+XXXX'.
It does not specify 'how code U+XXXX is stored in a file'.
Storing files is the job of 'encoding schemes' such as UTF-8 and UTF-16.
Many people confuse Unicode with UTF-8. Remember this distinction: Unicode is the dictionary (defining which character maps to which number), UTF-8 is the writing rule (defining how a number is written as a byte sequence).
UTF-8: the most popular Unicode encoding scheme
The design of UTF-8 is extremely clever. It is a variable-length encoding:
- ASCII characters (U+0000 ~ U+007F): stored in 1 byte
- Most European and Arabic characters: 2 bytes
- Chinese, Japanese, Korean: 3 bytes
- Supplementary characters (including most emoji): 4 bytes
UTF-8 encoding rules
U+0000~U+007F
0xxxxxxx
1 byte, 7 bits of data
U+0080~U+07FF
110xxxxx
10xxxxxx
2 bytes, 11 bits of data
U+0800~U+FFFF
1110xxxx
10xxxxxx
10xxxxxx
3 bytes, 16 bits of data
U+10000~U+10FFFF
11110xxx
10xxxxxx
10xxxxxx
10xxxxxx
4 bytes, 21 bits of data
The leading bit pattern of the first byte tells the decoder how many bytes this character uses.
- Starts with 0: single-byte character
- Starts with 110: two-byte character
- Starts with 1110: three-byte character
- Starts with 11110: four-byte character
- Continuation bytes all start with 10
UTF-8's greatest advantage: full compatibility with ASCII.
Any valid ASCII text is also valid UTF-8 text.
This property lets UTF-8 smoothly replace old ASCII systems without breaking any existing data.
Interactive demo: real-time encoding lookup
Enter any text below to see each character's Unicode code point, UTF-8 encoded bytes, and space used.
Quick fill:
Mixed Chinese and English
Uppercase A
Lowercase a
Digit
All English
All Chinese
Uppercase/lowercase comparison
Operation suggestions:
- Enter pure English and observe that each character takes only 1 byte.
- Enter Chinese and observe that each Chinese character takes 3 bytes.
- Input
Hello RUNOOB, and notice whether the ASCII codes of each letter are arranged consecutively. - Compare the binary of uppercase and lowercase letters and find the letter pairs that differ by only 1 bit (such as A and a).
Garbled text: principles and prevention
The essence of garbled text is just one sentence: using the wrong dictionary to interpret data.
Suppose a file stores three bytes of UTF-8 encoding:E4 BD A0
- Decode as UTF-8: these 3 bytes form one character -> 'Ni' (a Chinese character)
- Decode as GBK: E4 BD is treated as one GBK two-byte character -> possibly some unrelated Chinese character
- Decode as Latin-1: E4, BD, A0 are treated as three separate Western European characters -> garbled text like 'a + 1/2 + nbsp'
The same binary, three dictionaries read out three different texts.
How to avoid garbled text?
- Use UTF-8 everywhere: modern Web, APIs, and databases almost all default to UTF-8
- Explicitly declare the encoding: in HTML write
, and in the HTTP response header writeContent-Type: text/html; charset=utf-8 - Editor settings: editors like VS Code and Sublime all support setting the file encoding to UTF-8
BOM (Byte Order Mark) issues
Although UTF-8 does not need to worry about byte order (because it works byte by byte), some Windows programs add a BOM at the start of UTF-8 files:EF BB BF.
These three bytes are used to mark 'this file is UTF-8 encoded'.
But on Unix/Linux systems, a BOM can cause various problems:
- On the first line of a shell script
#!/bin/bashthere are three extra invisible bytes in front, causing the script to fail to execute - If a PHP file has a BOM, it may trigger a 'headers already sent' error
- A JSON parser may reject JSON data starting with a BOM
Recommendation: use 'UTF-8 without BOM' for UTF-8 files, which is also the default of most modern editors.
Code demo: encoding and decoding
Example
Complete character encoding demo (runoob demo)
import
sys
=============================================
Demo 1: basic usage of ord() and chr()
=============================================
(
"="
60
)
(
"Demo 1: conversion between characters and code points"
)
(
"="
60
)
ord() gets the Unicode code point of a character
text
=
"Hello RUNOOB"
for
ch
in
text:
cp
=
ord
(
ch
)
(
f
" '{ch}' -> code point U+{cp:04X} (decimal {cp})"
)
(
)
chr() gets the character from a code point
for
cp
in
[
65
,
97
,
48
,
0x4F60
,
0x597D
]
:
ch
=
chr
(
cp
)
(
f
" code point U+{cp:04X} -> character '{ch}'"
)
=============================================
Demo 2: encode into a byte sequence (encode)
=============================================
(
"\n"
"="
60
)
(
"Demo 2: string -> UTF-8 byte sequence"
)
(
"="
60
)
texts
=
[
"A"
,
"Hello"
,
"Hello" (Chinese)
,
"RUNOOB tutorial"
]
for
text
in
texts:
utf8_bytes
=
text.
encode
(
'utf-8'
)
hex_str
=
utf8_bytes.
hex
(
' '
)
.
upper
(
)
(
f
"\nText: '{text}'"
)
(
f
" Number of characters: {len(text)}"
)
(
f
" UTF-8 byte count: {len(utf8_bytes)}"
)
(
f
" UTF-8 hex: {hex_str}"
)
Byte-by-byte analysis
(
f
" Byte breakdown:"
)
for
i
,
b
in
enumerate
(
utf8_bytes
)
:
bin_str
=
format
(
b
,
'08b'
)
Determine byte type
if
b
<
0x80
:
typ
=
"ASCII single byte"
elif
b
=
0xC0
and
b
<
0xE0
:
typ
=
"Two-byte leading byte"
elif
b
=
0xE0
and
b
<
0xF0
:
typ
=
"Three-byte leading byte"
elif
b
=
0x80
and
b
<
0xC0
:
typ
=
"Continuation byte"
else
:
typ
=
"other"
(
f
" Byte {i}: 0x{b:02X} = {bin_str} ({typ})"
)
=============================================
Demo 3: GBK encoding (a non-Unicode encoding commonly used in China)
=============================================
(
"\n"
"="
60
)
(
"Demo 3: GBK encoding (compared with UTF-8)"
)
(
"="
60
)
text
=
"Ni Hao RUNOOB"
utf8_bytes
=
text.
encode
(
'utf-8'
)
gbk_bytes
=
text.
encode
(
'gbk'
)
(
f
"Text: '{text}'"
)
(
f
" UTF-8 ({len(utf8_bytes)} bytes): {utf8_bytes.hex(' ').upper()}"
)
(
f
" GBK ({len(gbk_bytes)} bytes): {gbk_bytes.hex(' ').upper()}"
)
In GBK each Chinese character takes 2 bytes
(
f
"\n Note: in GBK a Chinese character takes 2 bytes, in UTF-8 a Chinese character takes 3 bytes"
)
(
f
" For Chinese text, GBK is more compact than UTF-8"
)
(
f
" But GBK does not support all Unicode characters (e.g. emoji)"
)
=============================================
Demo 4: decoding error scenarios
=============================================
(
"\n"
"="
60
)
(
"Demo 4: decoding error scenarios (the cause of garbled text)"
)
(
"="
60
)
Encode Chinese text with UTF-8
original
=
"Hello" (Chinese)
utf8_data
=
original.
encode
(
'utf-8'
)
(
f
"Original text: '{original}'"
)
(
f
"UTF-8 encoding: {utf8_data.hex(' ').upper()}"
)
Error 1: decode UTF-8 data with GBK
try
:
decoded_wrong
=
utf8_data.
decode
(
'gbk'
)
(
f
"Decoded with GBK: '{decoded_wrong}' (garbled!)"
)
except
Exception
as
e:
(
f
"GBK decoding failed: {e}"
)
Error 2: decode with Latin-1
decoded_latin
=
utf8_data.
decode
(
'latin-1'
)
(
f
"Decoded with Latin-1: '{decoded_latin}' (garbled text that looks like Western European characters)"
)
=============================================
Demo 5: building a sensible decoder
=============================================
(
"\n"
"="
60
)
(
"Demo 5: encoding detection and safe decoding"
)
(
"="
60
)
def
safe_decode
(
data
,
encodings
=
[
'utf-8'
,
'gbk'
,
'latin-1'
]
)
:
"""Try decoding with several encodings, return the first successful result"""
for
enc
in
encodings
:
try
:
return
data.
decode
(
enc
)
,
enc
except
(
UnicodeDecodeError
,
LookupError
)
:
continue
return
data.
decode
(
'latin-1'
,
errors
=
'replace'
)
,
'latin-1 (fallback)'
Testing
test_cases
=
[
"Hello RUNOOB"
.
encode
(
'utf-8'
)
,
"Ni Hao Shi Jie"
.
encode
(
'utf-8'
)
,
"Ji Suan Ji"
.
encode
(
'gbk'
)
,
]
for
data
in
test_cases:
result
,
encoding
=
safe_decode
(
data
)
(
f
" Data ({len(data)} bytes) decoded with {encoding}: '{result}'"
)
(
"\n"
"="
60
)
(
"Summary: a string is Python's internal representation; encoding is the format used for storage/transmission."
)
(
"Always do encoding conversion at I/O boundaries; internally always use the str type."
)
(
"="
60
)
The present and future of character encoding
As of today, UTF-8 has become the de facto standard of the Internet.
Over 98% of web pages use UTF-8 encoding.
The JSON specification requires UTF-8.
Almost all modern programming languages use UTF-8 by default to handle text.
Unicode is still expanding.
New versions of Unicode add new characters every year, including: rare scripts, historic scripts, new emoji.
Encoding has shifted from the question of 'can it be represented' to 'how to store and transmit it efficiently'.
If you start a new project today, choosing UTF-8 cannot go wrong. It is backward compatible with ASCII, cross-platform, and supports all languages. The only thing to watch -- make sure your whole stack (front end, back end, database) uses UTF-8 and does not mix encodings.