Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

How characters are represented -- ASCII and Unicode

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:

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):

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:

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.

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:

  1. Enter pure English and observe that each character takes only 1 byte.
  2. Enter Chinese and observe that each Chinese character takes 3 bytes.
  3. Input Hello RUNOOB, and notice whether the ASCII codes of each letter are arranged consecutively.
  4. 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

The same binary, three dictionaries read out three different texts.

How to avoid garbled text?

  1. Use UTF-8 everywhere: modern Web, APIs, and databases almost all default to UTF-8
  2. Explicitly declare the encoding: in HTML write , and in the HTTP response header write Content-Type: text/html; charset=utf-8
  3. 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:

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()

=============================================

print

(

"="

60

)

print

(

"Demo 1: conversion between characters and code points"

)

print

(

"="

60

)

ord() gets the Unicode code point of a character

text

=

"Hello RUNOOB"

for

ch

in

text:

    cp

=

ord

(

ch

)

   

print

(

f

" '{ch}' -> code point U+{cp:04X} (decimal {cp})"

)

print

(

)

chr() gets the character from a code point

for

cp

in

[

65

,

97

,

48

,

0x4F60

,

0x597D

]

:

    ch

=

chr

(

cp

)

   

print

(

f

" code point U+{cp:04X} -> character '{ch}'"

)

=============================================

Demo 2: encode into a byte sequence (encode)

=============================================

print

(

"\n"

"="

60

)

print

(

"Demo 2: string -> UTF-8 byte sequence"

)

print

(

"="

60

)

texts

=

[

"A"

,

"Hello"

,

"Hello" (Chinese)

,

"RUNOOB tutorial"

]

for

text

in

texts:

    utf8_bytes

=

text.

encode

(

'utf-8'

)

    hex_str

=

utf8_bytes.

hex

(

' '

)

.

upper

(

)

   

print

(

f

"\nText: '{text}'"

)

   

print

(

f

" Number of characters: {len(text)}"

)

   

print

(

f

" UTF-8 byte count: {len(utf8_bytes)}"

)

   

print

(

f

" UTF-8 hex: {hex_str}"

)

   

Byte-by-byte analysis

   

print

(

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"

       

print

(

f

" Byte {i}: 0x{b:02X} = {bin_str} ({typ})"

)

=============================================

Demo 3: GBK encoding (a non-Unicode encoding commonly used in China)

=============================================

print

(

"\n"

"="

60

)

print

(

"Demo 3: GBK encoding (compared with UTF-8)"

)

print

(

"="

60

)

text

=

"Ni Hao RUNOOB"

utf8_bytes

=

text.

encode

(

'utf-8'

)

gbk_bytes

=

text.

encode

(

'gbk'

)

print

(

f

"Text: '{text}'"

)

print

(

f

" UTF-8 ({len(utf8_bytes)} bytes): {utf8_bytes.hex(' ').upper()}"

)

print

(

f

" GBK ({len(gbk_bytes)} bytes): {gbk_bytes.hex(' ').upper()}"

)

In GBK each Chinese character takes 2 bytes

print

(

f

"\n Note: in GBK a Chinese character takes 2 bytes, in UTF-8 a Chinese character takes 3 bytes"

)

print

(

f

" For Chinese text, GBK is more compact than UTF-8"

)

print

(

f

" But GBK does not support all Unicode characters (e.g. emoji)"

)

=============================================

Demo 4: decoding error scenarios

=============================================

print

(

"\n"

"="

60

)

print

(

"Demo 4: decoding error scenarios (the cause of garbled text)"

)

print

(

"="

60

)

Encode Chinese text with UTF-8

original

=

"Hello" (Chinese)

utf8_data

=

original.

encode

(

'utf-8'

)

print

(

f

"Original text: '{original}'"

)

print

(

f

"UTF-8 encoding: {utf8_data.hex(' ').upper()}"

)

Error 1: decode UTF-8 data with GBK

try

:

    decoded_wrong

=

utf8_data.

decode

(

'gbk'

)

   

print

(

f

"Decoded with GBK: '{decoded_wrong}' (garbled!)"

)

except

Exception

as

e:

   

print

(

f

"GBK decoding failed: {e}"

)

Error 2: decode with Latin-1

decoded_latin

=

utf8_data.

decode

(

'latin-1'

)

print

(

f

"Decoded with Latin-1: '{decoded_latin}' (garbled text that looks like Western European characters)"

)

=============================================

Demo 5: building a sensible decoder

=============================================

print

(

"\n"

"="

60

)

print

(

"Demo 5: encoding detection and safe decoding"

)

print

(

"="

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

)

   

print

(

f

" Data ({len(data)} bytes) decoded with {encoding}: '{result}'"

)

print

(

"\n"

"="

60

)

print

(

"Summary: a string is Python's internal representation; encoding is the format used for storage/transmission."

)

print

(

"Always do encoding conversion at I/O boundaries; internally always use the str type."

)

print

(

"="

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.