100% found this document useful (1 vote)
2K views568 pages

Microprocessor & Interfacing

The document is a textbook titled 'Microprocessors and Interfacing: Programming and Hardware' by Douglas V. Hall, published by McGraw-Hill in 1986. It covers various aspects of microprocessors, including programming, interfacing, and hardware design, focusing primarily on the Intel 8086 family of microprocessors. The book is intended for students in electrical and electronic engineering programs, as well as industry professionals seeking to enhance their knowledge of microprocessor technology.

Uploaded by

shahriarabid54
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
2K views568 pages

Microprocessor & Interfacing

The document is a textbook titled 'Microprocessors and Interfacing: Programming and Hardware' by Douglas V. Hall, published by McGraw-Hill in 1986. It covers various aspects of microprocessors, including programming, interfacing, and hardware design, focusing primarily on the Intel 8086 family of microprocessors. The book is intended for students in electrical and electronic engineering programs, as well as industry professionals seeking to enhance their knowledge of microprocessor technology.

Uploaded by

shahriarabid54
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 568

DouglasV.

Hall
MICROPROCESSOR.
ANDINTERFACING
programming
andHardware

\ m

m2222*2222222 22-2-2."
Digitized by the Internet Archive
in 2010

http://www.archive.org/details/microprocessorsiOOhall
MICROPROCESSORS
AND INTERFACING
Programming and Hardware

Douglas V. Hall

Gregg Division
McGRAW-HILL BOOK COMPANY
New York Atlanta Dallas St. Louis San Francisco
Auckland Bogota Guatemala Hamburg Lisbon
London Madrid Mexico Montreal New Delhi Panama Paris
San )uan Sao Paulo Singapore Sydney Tokyo Toronto
Sponsoring Editor: Paul Berk
Editing Supervisor: James Fields
Design and Art Supervisor/Cover Designer: Frances Conte Saraeco
Production Supervisor: Priscilla Taguer
Text Designer: Susan Brorein

Library of Congress Cataloging-in-Publication


Data
Hall, Douglas V., date.
Microprocessors and interfacing.
Includes index.
1. Microprocessors — Programming. 2. Micro-
processors.
Computer 3. interfaces. I. Title.
QA76.6.H2994 1986 005.26 86-156
ISBN 0-07-025526-1

The manuscript for this book was prepared elec-


tronically.

Microprocessors and Interfacing:


Programming and Hardware
Copyright C 1986 by McGraw-Hill. Inc. All rights
reserved. Printed in the United States of America.
Except as permitted under the United States
Copyright Act of 1976. no part of this publication
may be reproduced or distributed in any form or
by any means, or stored in a data base or retrieval
system, without the prior written permission of
the publisher.

5 6 7 8 9 0 SEMBKP 8 9 3 2 10 9
ISBN Q-07-0255Eb-l
CONTENTS
Preface v More Practice with Simple Sequence Pro-
grams 72
Flags, .Jumps, and WHILE-DO Implementa-
CHAPTER tion 77
REPEAT- UNTIL Implementation and Exam-
Computer Number Systems, Codes, and Digital ples 87
Debugging Assembly Language Programs l 00
Devices 1
Review Questions and Problems 102
Objectives 1
Computer Number Systems and Codes 1
Adding and Subtracting Binary. Oetal, Hex, and
BCD Numbers 10 CHAPTER
Basic Logic Gates 15
Review Questions and Problems 22 IF-THEN -ELSE Structures, Procedures, and
Macros 104
Objectives 104
CHAPTER IF-THEN, IF-THEN-ELSE. and Multiple IF-
THEN - ELSE Programs 104
Computers, Microcomputers, and Micro- Writing and Using Procedures 1 10
processors—
An Introduction 24 Writing and Using Assembler Macros 139
Review Questions and Problems 141
Objectives 24
Computers 24
The 8086. 8088. 80186. 80188, 80286 Micro-
processors—
Introduction 33 C H A P T E " 6
8086 Internal Architecture 33
Introduction to Programming the 8086 37 8086 Instruction Descriptions and Assembler Di-
Review Questions and Problems 41 rectives 144
Instruction Descriptions 144
Assembler Directives 174
CHAPTER

8086 Family Assembly Language Programming CHAP TER 7


— Introduction 43
Objectives 43 8086 System Connections, Timing, and Trouble-
Program Development Steps 43 shooting 179
Constructing the Machine Codes for 8086 In- Objectives 179
structions 54 8086 Hardware Review 179
Writing Programs for Use With an As- Addressing Memory and Ports in Microcomputer
sembler 60 Systems 196
Assembly Language Program Development 8086 Timing Parameters 209
Tools 65 Troubleshooting a Simple 8086-based Microcom-
Review Questions and Problems 69 puter 213
Review Questions and Problems 219

CHAPTER

CHAP T ER 8
8086 Assembly Language Programming Tech-
niques—
Part 1 72 Interrupts and Interrupt Service Proce-
Objectives 72 dures 221
Objectives 221
8086 Interrupts and Interrupt Responses 221 CHAPTER 12
Hardware Interrupt Applications 232
Review Questions and Problems 258 Microcomputer System Peripherals 406

Objectives 406
Microcomputer Displays 406
CHAPTER .7 Raster Scan CRT Graphics Displays 413

CRT Terminals 414


Digital Interfacing 261 Raster Scan Color Graphics 415
Objectives 261 Vector Scan CRT Displays 4 18
Alphanumeric/Graphics LCD Displays 419
Programmable Parallel Ports and Handshake
Input/Output 261 Computer Vision 4 19
Interfacing a Microprocessor to Keyboards 280 Mass Data Storage Systems 422
Interfacing to Alphanumeric Displays 287 Floppy Disk Data Storage 422
Interfacing Microcomputer Ports to High-Power Magnetic Hard Disk Data Storage 431
Devices 298 Optical Disk Data Storage 432
Optical Motor Shaft Encoders 304 Printer Mechanisms 434
Review Questions and Problems 307 Speech Synthesis and Recognition With a Com-
puter 437
Review Questions and Problems 440

CHAPTER 10
Analog Interfacing and Industrial Control 311 CHAPTER 13
Objectives 311
Data Communication and Networks 442
Review of Operational-Amplifier Characteristics
and Circuits 311 Objectives 442
Sensors and Transducers 316 Asynchronous Serial Data Communication 442
D/A Converter Operation, Interfacing, and Appli- Serial Data Transmission Methods and Stan-
cations 321 dards 448
A/D Converter Types, Specifications, and Inter- Asynchronous Communication Software on the
facing 324 IBM PC 461
A Microcomputer-Based Scale 328 Synchronous Serial Data Communication and
A Microcomputer-Based Industrial Process-Con- Protocols 477
trol System 340 Local Area Networks 481
An 8086-Based Process-Control System 342 Review Questions and Problems 487
Developing the Prototype of a Microcomputer-
Based Instrument 355
Digital Filters
Review Questions
357
and Problems 359
CHAPTER 14
Operating Systems, the 80286 Microprocessor,
and the Future 490
CHAPTER 11 Objectives 490
Multiple Microprocessor Systems and Operating System Concepts and Terms 490
The Unix Operating System 496
Buses 361 The INTEL RMX 86™ Operating System 499
Objectives 361 The INTEL 80286 Microprocessor 502
The 8086 Maximum Mode 361 New Directions 513
Direct Memory Access (DMA) Data Transfer 363 Epilogue 516
Interfacing and Refreshing Dynamic RAM 370 Review Questions and Problems 5 17
Processors With Integrated Peripherals — The
80186 and 80188 374
A Coprocessor — The 8087 Math Coproces- Bibliography 519
sor 377 Appendix A 521
Multiple Bus Microcomputer Systems 397 Appendix B 533
Review Questions and Problems 404 Index 547
CONTENTS
PREFACE
For the most part. Microprocessors and Interfac write, lest . ;ind debug. Experience hasshownthat
tng: Programming and Hardware is based on a the most successful approach to writing a pro
throe-quarter series of microprocessor courses gram is to solve the problem fust . and then simply
that my colleagues and I teach. The book is in- implement the solution in the desired program-
tended
students
tor in electrical engineering pro- ming language.
grams, students
in electronic engineering techni- The 8086 instructions are introduced in Chap
cian trainingprograms, and people working in ters 2 through 5, as they are needed to solve sim-
industry who want to upgrade their knowledge of ple programming problems. Chapter 6 contains a
microprocessors. dictionary of all the 8086 and 80 186 instructions.
Before reading this book, you should have some You can refer to this chapter to find further details
basic knowledge of diodes, transistors, and digital about an instruction you want to use to do a par-
circuitry. One of its aims is to teach you how to ticular operation
in a program.
decipher and use manufacturer's literature; ac- Chapter 7 discusses the hardware signals, tim-
cordingly,
relevant
many parts of data sheets are ing, and
system connections of a simple micro-
shown. Because of the large number of actual de- computer. Chapter
7 also teaches a systematic
vices discussedhere, it was impossible to put the approach to troubleshooting a malfunctioning
complete data sheets for all these devices in the 8086-based system. The remaining chapters
appendixes. Therefore, I strongly suggest that you show how the hardware and the programs work
acquire or gain access to the latest edition of the together. Troubleshooting a microprocessor-
Intel Microsystem Components Handbook so based system, for example, usually requires
that, as you work your way through this book, you knowledge of both its hardware and program-
can refer to it if you need further information ming,I discuss
so here how diagnostic routines
about a particular device. The bibliography lists are written and used to find a problem.
other materials I have found useful. Chapter 8 discusses how the 8086 responds to
I have chosen here to teach the programming, interrupts and how interrupt service procedures
system connections, and interfacing of 16-bit mi- are written and used. Chapters 9 through 13 de-
croprocessors,
function
which as the "brains" of scribe
detail
in how a microcomputer is interfaced
microcomputers such as the IBM PC. My experi- with a wide variety of devices and systems. Also
encean as engineer and as a teacher indicates these chapters describe how the hardware and
that it is more productive to learn one micropro- programs for microprocessor-based products are
cessor familyvery thoroughly, and from that developed. Finally, Chapter 14 discusses operat-
strong base learn other families as needed. There- ing systemprograms, and the 80286 and 80386
fore, thisbook concentrates on the Intel microprocessors that are designed to be used as
8086/8088/80 186/80 188/80286/80386 family the brains of multiuser microcomputer systems.
of microprocessors, rather than superficially cov- Program development for 16-bit microproces-
eringmicroprocessor
the families of several man- sorssomewhat
is tedious on hex-keypad-type de-
ufacturers. velopmentsuchboardsas we used for 8-bit pro-
I came into the world of electronics through the cessors. Furthermore, industry does not usually
route of vacuum tubes. Therefore, my first tend- develop microprocessor-based products in this
ency was to approach microprocessors from a manner. Therefore, for working with 16-bit pro-
hardware orientation. However, the more I de- cessors
recommend
I a systems approach. A mi-
signed with
microprocessors and taught micro- croprocessor development
system, an IBM PC, or
processor classes,
the more I became aware that IBM PC-compatible computer, can be used to edit,
the real essence of a microprocessor is what you assemble, link/locate, run, and debug 8086 as-
can program it to do. For this reason the book sembly language programs. For programs that re-
begins with just a brief overview of the hardware quire external hardware, the object code for these
of a computer. The next five chapters show how a programs can be downloaded to some prototype
microprocessor-based microcomputer can be pro- hardware such as an Intel SDK-86 development
grammed
do someto real tasks. board. Chapter 13 contains a program that allows
The emphasis throughout is on writing assem- you to download object code programs from an
bly languageprograms in a top-down structured IBM or IBM-compatible computer to an SDK-86
manner. The idea is to make programs easy to board. An available laboratory manual, written to
accompany this book, shows you how to use the merous
mention.
to Thanks to Lee Campbell of
SDK-86 board and an IBM PC-compatible com- Spokane Community College in Spokane, Wash-
puterassembly
for language programming and ington,meticulously
who worked his way through
interfacing. the manuscript and made many valuable sugges-
In the interfacing sections of this book I have tions. Thanks
to Wayne J. Vyrostek of Westark
tried to show as many circuits as possible that you College in Fort Smith, Arkansas, who reviewed
can build, add to your microcomputer, and exper- the manuscript and contributed several valuable
iment with.
Building and experimenting with real suggestions. Thanks to Intel Corporation for let-
circuits will help you become fluent with micro- ting use
me many drawings from their data books,
processors.
circuits
The in this book are intended so that this book could lead readers into the mate-
just as starters. Hopefully you will grow far rial they
can use to continue their learning. Fi-
beyond what is shown here, if you have sugges- nally, thanks
to my family and friends for their
tionsimproving
for this book or ideas that might patience and support during the long effort of
clarify a point for someone else, please communi- writing this book.
cate with
me.
I wish to express my profound thanks to the Douglas V. Hall
people who helped make this book a reality.
Thanks to Pat Hunter, without whose cheerful en-
couragement
might not I have made it through the
book. She proofread and coded the manuscript, DEDICATION

worked out the answers to the end-of-chapter


problems to verify that they are solvable, and To my students — Who grow beyond what I give
made many suggestions and contributions too nu- and return to pull me into the future with them.
CHAPTER

Computer Number Systems,


Codes, and Digital Devices

Before starting our discussion ol microprocessors and The number ol symbols needed in any base numbei sys
microcomputers we need to make sure that some key tern is equal to the base number. In the decimal numbei
concepts ol the number systems, codes, and digital de- system then, there are 10 symbols, 0 through 9. When
vires used in microcomputers are fresh in your mind. If the count in any digit position passes that ol the highest
the short summaries of these concepts in this chapter value symbol, a carry of 1 is added to the next digit posi-
are not enough to refresh your memory, then it is a good tion and
the other digit rolls back to zero. A car odome-
idea to review them in a current digital text before going ter ais good example of this.
on in this book. A number system can be built using powers of any
number as place holders or digits, but some bases are
more useful than others. It is difficult to build electronic
OBJECTIVES circuits which can store and manipulate 10 different
voltage levels but relatively easy to build circuits which
At the conclusion of this chapter you should be able to:
can handle two levels. Therefore, a binary or base -2
number system is used.
1. Convert numbers between the following codes: bi-
nary, octal,
hexadecimal, and BCD.

2. Define the terms bit. nibble, byte, word, most signif- The Binary Number System
icant bit.
and least significant bit. Figure lib shows the value of each digit in a binary
number. Each binary digit represents a power of 2. A
3. Use a table to find the ASCII or EBCDIC code for a
binary digit is often called a bit. Note that digits to the
given alphanumeric character.
right of the binary point represent fractions used for
4. Perform addition and subtraction of binary, octal, numbers less than one. The binary system uses only two
hexadecimal, and BCD numbers. symbols, zero (0) and one (1). Therefore, in binary you
count as follows: 0, 1, 10. 11. 100. 101. 110. Ill, 1000.
5. Describe the operation of gates, nip-flops, latches,
ri(
registers, ROMs, dynamic RAMs, static RAMs. and Binary numbers are often called binary words or just
buses. ifords. Binary words of certain numbers of bits have
6. Describe how an arithemtic logic unit can be in- also acquired special names. A 4-bit binary word is
structed
perform
to arithmetic or logical operations
on binary words.
5 3 4 6 7 2
103 102 10' 10° 10 ' 10 2
COMPUTER NUMBER SYSTEMS AND
CODES

Review of Decimal System 10 110 1 1


To understand the structure of the binary number sys- 2' 26 2" 24 23222'2° 2~'2~;
tem, the
first step is to review the familiar decimal or
base- 10 number system. Figure 1-la shows a decimal 1286432 16 8 4 2 1 i j
number with the value of each place holder or digit ex-
pressed
a power
as of 10. The digits in the decimal num-
ber 5346.72 then tell you that you have 5 thousands, 3 FIGURE 1-1 Digit values in decimal and binary.
hundreds. 4 tens, 6 ones. 7 tenths, and 2 hundredths. fa) Decimal, (b) Binary.
25 2" 23 22 21 2° reverse of the binary-to-decimal method above. For ex-
32 16 8 4 2 1 ample,
convert
to the decimal number 21 (sometimes
written as 21,,,) to binary, first subtract the largest
0 1 0 1 0 1n
power of 2 that will fit in the number. For 21 10 the larg-
est power of 2 that will fit is 16 or 24. Subtracting 16
from 21 gives a remainder of 5. Put a one in the 24 digit
227,0 = position and see if the next lower power of 2 will fit in
the remainder. Since 2A is 8 and 8 will not fit in the
Least Significant
remainder of 5. put a zero in the 2 ' digit position. Then
Binary Digit
try the next lower power of 2. In this case the next is 22
1
or 4. which will lit in the remainder of 5. A 1 is, there-
R] x 1 1 fore, put
in the 22 digit position. When 22 or 4 is sub-
R\ x 2 2
tracted from
the old remainder of 5 a new remainder of 1
is left. Since 21 or 2 will not fit into this remainder, a
no x 4 0 zero is put in that position. A 1 is put in the 2" position
because 2° is equal to 1 and this fits exactly into the
RQ x 8 0
remainder of 1. The result shows that 21,0 is equal to
RQ x 16 0 10101 in binary. The conversion process is somewhat
messy to describe, but easy to do. Try converting 46 10 to
R) x 32 32
binary. You should get 101 1 10.
R] x 64 64 Another method of converting a decimal number to
binary is shown in Figure l-2b. Divide the decimal
R] x 128 128
number by 2 and write the quotient and remainder as
1 227 Check shown. Divide this quotient and following quotients by
Most Significant 2 until the quotient reaches zero. The column of re-
Binary Digit mainders
be will
the binary equivalent of the given deci-
mal number. Note that the MSD is on the bottom of the
227,
column and the LSD is on the top of the column if you
perform the divisions in order from the top to the bot-
tomthe
of page. You can demonstrate that the binary
MSD Check
number is correct by reconverting from binary to deci-
2 • 625 = ^25 1 x .5 mal as
shown in the right-hand side of Figure l-2b.

2 ' 25^^ ^cj.50 0 • 25


You can convert decimal numbers
narysuccessive
by multiplication
less than 1 to bi-
by 2, and recording
2 x
.50 *"^ i!oo 1 %
125 carries until the quantity to the right of the decimal
625 point becomes zero, as shown in Figure l-2c. The car-
LSD ries representthe binary equivalent of the decimal num-
(c) ber, with
the most-significant bit at the top of the col-
umn. Decimal 0.625 equals 0.101 in binary. For
FIGURE 1-2 Converting decimal to binary, (a) Digit value decimal values that do not convert exactly the way this
method. (6.) Divide by 2 method, (c) Decimal fraction one did (quantity to the right of the decimal never be-
conversion. comes zero),
you can continue the conversion process
until you get the number of binary digits desired.
called a nibble, and an 8-bit binary word is called a byte. At this point it is interesting to compare the number
A 16-bit binary word is often referred to just as a word. of digits required to express numbers in decimal with
and a 32-bit binary word is referred to as a doubleword. the number required to express them in binary. In deci-
The rightmost or least-significant l)it of abinary word is mal, one
digit can represent 101 numbers. 0—9; two dig-
usually referred to as the LSB. The left most or most-sig- its canrepresent 102 or 100 numbers. 0-99; and three
nificant
of bit
a binary word is usually called the MSB. dibits can represent 10* or 1000 numbers. 0-999. In
To convert a binary number to its equivalent decimal binary, a similar pattern exists. One binary digit can
number multiply each digit times the decimal value of represent two numbers. 0—1; two binary digits can rep-
the digit and just add these up. The binary number 101, resent
or 224 numbers. 0—11; and three binary digits
for example, represents: (1 • 22) + (0 • 21 ) + ( 1 % 2°) can represent 2 4 or 8 numbers. The pattern then is that
or 4 + 0 + 1 = decimal 5. For the binary number N decimal digits can represent 10N numbers and N bi-
101 10. 1 1 you have: nary digits
can represent 2N numbers. Eight binary dig-
its canrepresent the 2H or 256 numbers. 0—255.
(1 •- 24) + (0 % 23) + (1 < 22) + (1 % 2'1
+ (0 • 2"] Ml -2 '1 + (1 • 2 '-')
= 16 + 0 + 4 + 2 + 0 + 0.5 + 0.25 Octal
= decimal 22.75
Binary is not a very compact code. This means that it
To convert a decimal number to binary there are two requires many more digits to express a number than
common methods. The first (Figure l-2a) is simply a does, for example, decimal. Twelve binary digits can only

CHAPTER ONE
4096 512 64 8 1 which groups the binary digits in groups ol four rathei
than three Hexadecimal oi base 16 code does this. Fig-
ureIdI shows the digil values foi hexadecimal, which
Is often | ust called lt<-\ Sim e hex is base M>. you have to
have 16 possible symbols for each digit. The tabli of 1 '
in i' I l/) shows the symbols foi hex code. Aftei the deci
327
J*- ' Decimal = "> 327D = 5078 111.11 symbols 0 through 9 air used up. you use the let! cis
A through F foi values l<> through 15.
As mentioned above, each hex digit is equal to foui
8J327 = 40 binary digits. To convert the binary number 1 10101 10

8j~40 = 5
16' 16-' 16' 16°. 16 ' 16 ' 16 '
8j 5 = 0
4096 256 16 1 ,'„ ,,',

(a)

Dec Hex
Binary 101 011 111 .
0 0
Octal
Binary Point
1
1 1

2 = 2
FIGURE 1-3 Octal numbers, (a) Value of place holders. 3 = 3
(b) Conversion of decimal to octal, (c) Conversion of
binary to o( tal. 4 = 4

5 = 5

describe a number up to 4095,,,. Computers require 6 = 6

binary data, but people working with computers have 7 = 7


trouble remembering the long binary words produced by
the noncompact code. One solution to the problem is to 8 = 8

use the octal or base-8 code. As you can see in Figure 9 = 9


l-3a, the digits in this code represent powers of 8. The
symbols then are 0 through 7. You can convert a decimal 10 = A

number to the octal equivalent number with the same


11 = B
trick you used in convert decimal to binary. Figure l-3b
shows the technique for decimal-to-octal conversion. 12 = C
Decimal 327 is equal to 507,s. Verification of this is
13 = D
shown by reconverting the octal to decimal in the sec-
ond half
of Figure l-3b. 14 = E
Since 8 is an integral power of 2. conversions from
15 F
binary to octal, and octal to binary, are quite simple. If
you have a binary number such as 10101 1111. then, ib)
starting from the binary point and moving to the left,
1101 1D1102
mark off the binary digits in groups of three, as shown
in Figure 1-3c. Each group of three binary digits is equal D 6 HEX
to one octal digit. For the example above. Ill is a 7. 01 1
(c)
is a 3, and 101 is a 5. Therefore. 101011111 binary is
equal to 537,s.
22710 = ? H6;
You convert from octal to binary by replacing each
octal digit with its 3-bit binary equivalent. 16J227" = 14 R3 x 1 = 3

16pc4 = 0 RE x 16 = 224
Hexadecimal 22 7

Some once-popular minicomputers, such as the PDP-8,


have 12 parallel data lines. Four octal digits are an easy 227, E3,6
way to represent the binary data word on these 12 paral-
lel lines. For example. 100001010111 binary is easily
remembered or written as 4127 octal. Most microproc- FIGURE 1-4 Hexadecimal numbers, (a) Value of place
essors have
4-bit. 8-bit. 16-bit. or 32-bit data words. For holders, (b) Symbols, (c) Binary to hexadecimal
these microprocessors, it is more logical to use a code conversion, (d) Decimal to hexadecimal conversion.

COMPUTER NUMBER SYSTEMS, CODES, AND DICITAt DEVICES


z 5
o _l
a. o -- w n rr in to r^ oo o) < co O Q LU LL
II
CO
5

O
-1
a
(0 u. i- o o o t- t- i- o ,- t- O r- O O t- r-
5
i- UJ T- O T- O O O t- o ,- o t- i-
z
UJ
Q r- O t- i- O i- t- o ,- O *- t- T- T- T- O
S
o
LU O t- O o
CO u
z
LU CO T- O O T- ,- ,- t- O O r- r- O
>
UJ
CO ,- O T- 1- O T- T- T" T- T- T- O O O t- i-

REFLECTED
CODE
GRAY
O
O
o
o

i-
T-
O
o
o

O
T~
t-
o
o

T-
O
i-
o
o

O
O
*-

o
T-
t-

o
T-
o

o
O
o

o
O
O
i-
O
*-
T-
o
T-
O
1-
o
i-
T-
o
i-
O
o
p
P
o

CO
CO
CO
T-
O
o
O
T-
o
O
T-
o
T-
T-
o
1000
0111 1010
1001 1100
1011 )0100
)0011 1000
0100
0100
0110
0100
0111
0100
0101
UJ
u
X o o o o
UJ
o o o o p p t- t-
o o o o o o o o o o o o

O 1- O T" O O t- o

CO
CM
O
o
o
O
o
o
T"
o
o
T-
o
o
o
i-
o
o
o
o
i-
o 1100
1011 0000 1000
0001
0010
0001
000110001
0100
0001
001
0001
UJ
a in
o
o
-i
< O i- O 1-
s
o CM
o
o
o
p
o
o
t-
o
o
i-
o
o
0010
OOLL
LLOL 1110
LOLL1111 0010
0001
0000
0001
00010100
0001
0011
0001
1011
0001
UJ
t
Q CM

O i- O i- O t- O i-
a
o
m
O
o
o
O
o
o
i-
o
o
T-
o
o
O

o
O

o
T-

o
T~

o
10000000
0001
1001
00010100
0001
0010
0001
0101
0001
0011
0001
CM

CO

<1
X s O «- CM CO t 111 (O N co a> < cd O O LU LI-
UJ u
X UJ
a

_i
LU O f- CM CO 'S- id co r^
Q O t- CM CO « K) (O s

0 o
o
u
LU >
CO E O i- O 1- O i- O T- Q i- O i- O i- O i-
< O O t- t- O O t- •>- S p i- r- O O i- i-
o o o o o o o o
z o o o o
Zj o o o o
CD

r- Z
r-0
uuS is O f- CM CO m- lo to r~- CO en O r- CM CO %* LO

II 3 «

CHAPTER ONE
id hex, mark off groups ol four, moving to the left from r I 1/

the binary point, .is shown In Figure l 4c. Then write


the hex symbol foi the value ol each group ol four The
ol 10 uk nip Is equal to 6 and the 1 101 group Is equal to
13. Since 13 is Din hex. 110101 10 binary is equal to D6 / /
y. y.
U1AJ
in hex. II is usually used after a numbei to indicate
that It is a hexadecimal number. For example, I >«i hex is
usually written D6H. Eighl bits require only two hex
(limits id represenl them
11 you want to convert from decimal to hexadecimal,
Figure I 4d shows .i familiar trick to do this. The resull
shows that 227i0 is equal to E3H. As you can sec. hex is
an even more compact code than decimal. Two hexadec
unal digits can indicate a number up to 255. Only four
hex ilii^iis ,uc needed to represenl a 16-bit binary num
her.
To Illustrate how hexadecimal numbers are used in
digital logic, a service manual tells yon that the 8-bit-
wide data bus of an 8088A microprocessor should con- HGURt l-d Seven-segment LLD display. (a) Segmenl
tain 3FHduring a certain operation. Converting 3FH to labels, (b) Schematic of common-cathode type.
binary' gives the pattern ol Is and O's (001 1 11111 yon (c) Schematic of common-anode type.
would expect to find with your oscilloscope or logic ana-
lyzerthe
on parallel lines. The 3FH is simply a short-
hand whichis easier to remember and less prone to er- binary digit changes at a time as you count up in this
rors. code.
To convert from octal code to hex code, the easiest way If yon need to construct a Gray-code table larger than
is to write the binary equivalent of the octal and then that in Table 1 - 1. a handy way to do so is to observe the
convert the binary dibits, four at a time, into the appro- pattern of Is and O's and just extend it. The least-signif-
priatedigits.
hex Reverse the procedure to get from hex icant digit
column starts with one 0 and then has alter-
to octal. nating groups
of two 1 s and two O's as you go down the
column. The second-most-significant digit column
starts with two O's and then has alternating groups of
four Is and four O's. The third column starts with four
BCD Codes
O's, then has alternating groups of eight Is and eight
O's. By now you should see the pattern. Try to figure out
STANDARD BCD
the Gray code for the decimal number 16. You should
In applications such as frequency counters, digital volt- get 11000.
meters,
calculators,
or where the output is a decimal
display, a binary-coded decimal or BCD code is often
used. The advantage of BCD for these applications is
that information for each decimal digit is contained in a Seven-Segment Display Code
separate 4-bit binary word. As yon can see in Tabic 1-1, Since seven-segment displays such as that shown in
the simplest BCD code uses the first 10 numbers of Figure 1-6 are now so common in everything from calcu-
standard binary code for the BCD number 0 through 9. lators
gasoline
to pumps, the segment code for these has
The hex codes A through F are invalid BCD codes. Each been included in Table 1-1. Some single seven-segment
decimal digit then is individually represented by its displays will display the last six numbers ( 10—15) of this
4-bit binary equivalent. Figure 1-5 illustrates this. code as the hexadecimal digits A-F. In Table 1-1, a 1
indicates that the segment is lit. which is true for dis-
GRAY CODE plays such
as the common-cathode light-emitting diode
(LED) display in Figure l-6b. For some displays, such as
Gray code is another important binary code which is
often used for encoding shaft position data from ma- the common-anode LED display shown in Figure l-6c, a
low actually lights the segment, so you have to invert all
chines such
as computer-controlled lathes. This code
has the same possible combinations as standard binary, the values.
but as you can see in the 4-bit example in Table 1- 1. they
are arranged in a different order. Notice that only one
Alphanumeric Codes
When communicating with or between computers you
5 2 9 Decimal
need a binary-based code which can represent letters ol
the alphabet as well as numbers. Common codes used
0101 0010 1001 BCD
for this have from 5 to 12 bits per word and are referred
FIGURE 1-5 Decimal to BCD conversion. to as alphanumeric codes. To detect possible errors in

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES


TABLE 1-2
COMMON ALPHANUMERIC CODES

HEX
HEX HEX HEX CODE
CODE CODE CODE SELEC- FOR HOL- HOLES
ASCII FOR 7-BIT BCDIC FOR EP EBCDIC FOR TRIC SELEC- LERITH PUNCHED CODE
SYMBOL ASCII SYMBOL BCDIC SYMBOL EBCDIC SYMBOL TRIC SYMBOL FOR HOLLERITH

N U L 0 0 N U L 0 0 N U L 12 0 9 8 1
S 0 H 0 1 S 0 H 0 1 S C H 12 9 1
S T X 0 2 S T X 0 2 S T X 12 9 2
E T X 0 3 E T X 0 3 E T X 12 9 3

EOT 0 4 EOT 3 7 E C T 9 7
E N Q 0 5 E N Q 2 D E N Q 0 9 8 5
A C K 0 6 A C K 2 E A C K 0 9 8 6
BEL 0 7 BEL 2 F BEL 0 9 8 7

B S 0 8 B S 1 6 B S 119 6
H T 0 9 H T 0 5 H T 12 9 5
L F 0 A L F 2 5 L F 0 9 5
V T 0 B X 9 A V T 0 B V T 12 9 8 3

F F 0 C F F 0 C F F 12 9 8 4
C R 0 D * F F C R 0 D C R 12 9 8 5
S 0 0 E S 0 0 E S 0 12 9 8 6
S 1 0 F S 1 0 F S 1 12 9 8 7

D L E 1 0 D L E 1 0 D L E 12 119 8 1
D C 1 1 1 D C 1 1 1 D C 1 11 9 1
D C 2 1 2 D C 2 1 2 D C 2 11 9 2
D C 3 1 3 D C 3 1 3 D C 3 119 3

D C 4 1 4 D C 4 3 5 D C 4 9 8 4
N A K 1 5 N A K 3 D N A K 9 8 5
S Y N 1 6 S Y N 3 2 S Y N 9 2
E T B 1 7 E 0 B 2 6 E T B 0 9 6

CAN 1 8 CAN 1 8 CAN 119 8


E M 1 9 E M 1 9 E M 119 8 1
SUB 1 A SUB 3 F SUB 9 8 7
ESC 1 B B Y P 2 4 ESC 0 9 7

F S 1 C F L S 1 C F S 119 8 4
G S 1 D G S 1 D G S 119 8 5
R S 1 E R D S 1 E R S 119 8 6
U S 1 F U S 1 F U S 119 8 7
S P 2 0 S P 0 0 S P 4 0 S P NO PNCH

I 2 1 1 6 A i 5 A \\ 2 7 i 12 8 7
2 2 4+f 5 F 7 F 2 D 8 7
# 2 3 # 4 B # 7 B # 7 E # 8 3
$ 2 4 $ 2 B $ 5 B $ 7 9 $ 11 8 3
% 2 5 % 5 C % 6 C % 3 D % 0 8 4

& 2 6 & 3 0 & 5 0 & 7 D 12


2 7 V 1 D 7 D 2 5 8 5
( 2 8 Blank 5 0 ( 4 D ( 3 8 ( 12 8 5

) 2 9 6 F ) 5 D ) 3 9 ) 11 8 5
2 A 6 C 5 C 7 C 118 4

(c ontinued)

CHAPTFK ONI
TABLE 1-2
COMMON ALPHANUMERIC CODES (CONTINUED)

HEX
HEX HEX HEX CODE
CODE CODE CODE SELEC FOR HOL- HOLES
ASCII FOR 7-BIT BCDIC FOR EP EBCDIC FOR TRIC SELEC LERITH PUNCHED CODE
SYMBOL ASCII SYMBOL BCDIC SYMBOL EBCDIC SYMBOL TRIC SYMBOL FOR HOLLERITH

t 2 B I 4 E i 0 E i 12 8 6
2 C 1 B 6 B 4 4 0 8 3
2 D 6 0 0 0 11
2 E 7 B 4 B 2 6 12 8 3
1 2 F 1 1 6 1 / 4 1 / 0 1

0 3 0 0 0 A 0 F 0 0 3 1 0 0
1 3 1 1 4 1 1 F 1 1 7 7 1 1
2 3 2 2 4 2 2 F 2 2 3 6 2 2
3 3 3 3 0 3 3 F 3 3 7 6 3 3
4 3 4 4 4 4 4 F 4 4 7 1 4 4

5 3 5 5 0 5 5 F 5 5 3 5 5 r)
6 3 6 6 0 6 6 F 6 6 3 4 6 6
7 3 7 7 4 7 7 F 7 7 7 5 7 7
8 3 8 8 4 8 8 F 8 8 7 4 8 8
9 3 9 9 0 9 9 F 9 9 3 0 9 9

3 A 4 D 7 A 4 D 8 2
3 B 2 E 5 E 4 5 118 6
< 3 C < 7 E < 4 C < 12 8 4
= 3 D V 0 F = 7 E = 0 6 = 8 6
> 3 E > 4 E > 6 E > 0 8 6
? 3 F ? 3 A ? 6 F ? 4 9 ? 0 8 7
,, 4 0 @ 0 C (a 7 C @ 3 E (1 8 4

A 4 1 A 7 1 A C 1 A 6 C A 12 1
B 4 2 B 7 2 B C 2 B 1 8 B 12 2
C 4 3 C 3 3 C C 3 C 5 C C 12 3
D 4 4 D 7 4 D C 4 D 5 D D 12 4

E 4 5 E 3 5 E C 5 E 1 D E 12 5
F 4 6 F 3 6 F C 6 F 4 E F 12 6
G 4 7 G 7 7 G C 7 G 4 F G 12 7
H 4 8 H 7 8 H C 8 H 1 9 H 12 8

I 4 9 I 3 9 I C 9 I 2 C 1 12 9
J 4 A J 2 1 J D 1 J 0 7 J 11 1
K 4 B K 2 2 K D 2 K 1 C K 11 2
L 4 C L 6 3 L D 3 L 5 9 L 11 3

M 4 D M 2 4 M D 4 M 6 F M 11 4
N 4 E N 6 5 N D 5 N 1 E N 11 5
0 4 F 0 6 6 0 D 6 0 6 9 0 11 6
P 5 0 P 2 7 P D 7 P 0 D P 11 7

Q 5 1 Q 2 8 Q D 8 Q 0 C Q 11 8
R 5 2 R 6 9 R D 9 R 6 D R 11 9
S 5 3 S 1 2 S E 2 S 2 9 S 0 2
T 5 4 T 5 3 T E 3 T 1 F T 0 3

[continued)

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES


TABLE 1-2
COMMON ALPHANUMERIC CODES (CONTINUED)

HEX
HEX HEX HEX CODE
CODE CODE CODE SELEC- FOR HOL- HOLES
ASCII FOR 7 BIT BCDIC FOR EP EBCDIC FOR TRIC SELEC- LERITH PUNCHED CODE
SYMBOL ASCII SYMBOL BCDIC SYMBOL EBCDIC SYMBOL TRIC SYMBOL FOR HOLLERITH

U 5 5 U 1 4 U E 4 U 5 E U 0 4
V 5 6 V 5 5 V E 5 V 6 E V 0 5
w 5 7 w 5 6 w E 6 w 2 8 w 0 6
X 5 8 X 1 7 X E 7 X 5 F X 0 7
Y 5 9 Y 1 8 Y E 8 Y 0 9 Y 0 8
z 5 A z 5 9 z E 9 z 3 F z 0 9

[ 5 B [ 7 D I A D [ 7 F I 12 8 2

\ 5 C \ 1 E N L 1 5 \ 0 8 2

I 5 D ] 2 D ] D D ] 11 8 2
A 5 E D 3 C "I 5 F A 11 8 7
5 F 6 0 6 D 0 8 0 8 5
6 0 RES 1 4 8 1

a 6 1 a 8 1 a 6 4 a 12 0 1
b 6 2 b 8 2 b 1 0 I. 12 0 2
t: 6 3 c 8 3 c 5 4 c 12 0 3
d 6 4 d 8 4 d 5 5 d 12 0 4

e 6 5 e 8 5 e 1 5 e 12 0 5
f 6 6 f 8 6 f 4 6 f 12 0 6

<J 6 7 g 8 7 g 4 7 g 12 0 7
h 6 8 h 8 8 h 1 1 h 12 0 8

i 6 9 i 8 9 i 2 4 i 12 0 9
I 6 A 1 9 1 i 0 7 1 12 111
k 6 B k 9 2 k 1 4 k 12 112
I 6 C 1 9 3 I 5 1 1 12 113

in 6 D m 9 4 m 6 7 m 12 11 4
n 6 E n 9 5 n 1 6 n 12 115
(i 6 F o 9 6 o 6 1 o 12 116
P 7 0 P 9 7 P 0 5 P 12 117

q 7 1 q 9 8 q 0 4 9 12 118
r 7 2 r 9 9 r 6 5 r 12 119
s 7 3 S A 2 s 2 1 s 11 0 2
t 7 4 t A 3 t 1 7 t 11 0 3

u 7 5 u A 4 u 5 6 u 110 4
V 7 6 V A 5 V 6 6 V 11 0 5
w 7 7 w A 6 w 2 0 w 110 6
X 7 8 X A 7 X 5 7 X 11 0 7

y 7 9 y A 8 y 0 1 y 110 8
z 7 A z A 9 z 3 7 z 110 9

1 7 B { 8 B ( 12 0
1 7 C 4 F 1 12 11
} 7 D } 9 B 1 11 0
~
7 E c 4 A - 11 0 1
DEL 7 F DEL 0 7 DEL 12 9 7

BCDIC SELECTRIC
HEX DIGIT HEX DIGIT R,,T,T, SR,4R,R,
PCBA 2 ' 2 • 2 ' 2° HEX DIGIT HEX DIGIT

( HAN Ik ONI
these codes, an additional bit. called a parity bit. is often TABLE 1-3
added as the mosl significanl bit. DEFINITIONS OF CONTROL CHARACTERS
/'(irin/ is a term used i<> Identifj whethei .1 data word
has .111 odd or even number of l's. II .1 data word con NUL NULL DC2 DIRECT CONTROL 2
tains an odd number ol l's. the word is said to have odd SOH START OF HEADING DC3 DIRECT CONTROL 3
parity rhe binary woi d 01 l 0 I l I with five l's has odd STX START TEXT DC4 DIRECT CONTROL 4

parity. The binary word 01 10000 has an even number ol ETX END TEXT NAK NEGATIVE

l's (two) so 11 has even parity EOT END OF TRANSMIS- ACKNOWLEDGE


SION SYN SYNCHRONOUS
In practice the pai ity bil may function as follows. The
ENQ ENQUIRY IDLE
system thai is sending a data word checks the parity ol
ACK ACKNOWLEDGE ETB END TRANSMIS-
the word. II the parity ol the da 1.1 word is odd. the sys
BEL BELL SION BLOCK
tern will set (he parity bil to a I - This makes the parity ol
BS BACKSPACE CAN CANCEL
the data word plus parity bil even. 11 the parity of the
HT HORIZONTAL TAB EM END OF MEDIUM
data \\ ord is even, the sending system will resel the par-
IF LINE FEED SUB SUBSTITUTE
ity bilto a 0. This again makes the parity of the data
VT VERTICAL TAB ESC ESCAPE
word plus parity even. The receiving system checks 1in-
FF FORM FEED FS FORM SEPARATOR
parity of the data word plus parity bil thai it receives. II
CB CARRIAGE RETURN GS GROUP SEPARATOR
the receiving system detects odd parity in the received
SO SHIFT OUT RS RECORD
data word plus parity, it can assume an error occurred
SI SHIFT IN SEPARATOR
and tells the sending system to send the data again. The
DLE DATA LINK ESCAPE US UNIT SEPARATOR
system is then said to be using even parity. The system
DC1 DIRECT CONTROL 1
could have been scl up to use (maintain) odd parity in a
similar manner.
The difficulty with this method of detecting errors in-
troduced during
transmission is that two errors intro-
duced into
a data word may keep the correct parity and, Interchange Code or EBCDIC. This is an 8-bit code
therefore, the parity checker won't indicate an error. without parity. A ninth bit can be added for parity. To
Other, more complex methods, such as CRC and "Ham- save space in Table 1-2, the eight binary digits ol
ming codes"can be used to detect multiple errors in EBCDIC are represented with their 2-digit hex equiva-
transmitted data, and even to correct errors. Some of lent.
these will be described in Chapters 12 and 13.
SELECTRIC
ASCII
Selectric is a 7-bit code used in the familiar IBM spin-
Table 1-2 shows several alphanumeric codes. The first of ning ball
typewriters and printers. Table 1-2 shows this
these is ASCII, or American Standard Code for Informa- code for reference also. Each bit position in the code
tion Interchange. This is shown in the lable as a 7-bit controls an operation of the spinning ball.
code. With seven bits you can code up to 128 characters, From most-significant to least-significant bit, the
which is enough for the full upper- and lower-case al- meaning of the seven bits are: ROTATE 5. TILT 1, TILT
phabet, numbers, punctuation marks, and control 2, SHIFT. ROTATE 2A, ROTATE 2. and ROTATE 1. In
characters. The code is arranged so that if only upper- addition to this 7-bit code. Selectrics have separate
case letters, numbers, and a few control characters are machine commands for space, return, backspace, tabs,
needed, the lower six bits are all that is required. If a bell, and index.
parity check is wanted, a parity bit is added to the basic
7-bit code in the MSB position. The binary word 1 100 HOLLERITH
0100. for example, is the ASCII code for upper-case D
Hollerith is a 12-bit code used to encode data from those
with odd parity. Table 1-3 gives the meanings of the con-
computer cards which threaten you with a fate worse
trol character symbols used in the ASCII code table.
than death if you "fold, spindle, or mutilate" them. Fig-
ure l-7b shows a standard 12-row by 80-column card.
BCDIC
The 12 data rows are referenced as. starting from the
BCDIC code is the Binary Coded Decimal Interchange top. 12. 11,0, 1.2.3.4,5,6,7,8.9. The top three rows
Code used with some computers. It uses seven bits plus are called zone punches and the bottom 10 rows are
a parity bit. The lower four bits are referred to as the called digit punches. Note that the zero row is included
numeric bits. The upper four bits contain a parity bit in both categories. A punched hole represents a 1 and a
and three zone bits. The arrangement of these bits is data word is described by the 12 bits in a vertical col-
shown at the bottom of Table 1-2. To save space in Table umn. The
card in Figure l-7b shows the Hollerith code
1-2. the hex equivalent of the binary digits is used for for the numbers and letters printed across the top of the
the BCDIC code expressed with even parity. card. Table 1-3 shows the entire code and the punched-
hole equivalent for each character. Since Hollerith code
EBCDIC uses very few of the possible combinations for 12 bits, it
Another alphanumeric code commonly encountered in is not very efficient. Therefore, it is usually converted to
IBM equipment is the Extended Binary Coded Decimal ASCII or EBCDIC for use.

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES


• •••

• •• • • • • ••••
•••• • • • • • • ••••• • ••••••

• •••
• •••• • • • • ••• • • ••
•••• •• •• • •• • ••••••• • ••

0 1 23456 789 ABCDEFGHIJKLMNOPQP.STUVWXYZ

ZONE
PUNCHES
iiiiiiiii i

0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 II IJ 0 '.
docoooooooooooggooooIIIIIIIIooooooIIooooooooogoooooooo OGC

1 I I II I I I I I I l| I I I Ill i 11 n ii i 1 1 11 1 i i i i i i i i i i i i n i i i i i ii i i i i i i i i i i i i i i i i i i i i I I 1

2222222 22 2 22 2|22 >222|22222222|2222222|22222222222222222222222222222222? 22 2


222;

I 3 ] 3 31 3 3 3 1 3 3 3 3 1 3 3 3 3 3 3 3 1 3 3 3 3 3 3 3 3 3 3 3 1 1 3 1 1 3 3 3 3 3 3 3 3 3 3 3 1 3 3 3 3 3 3 3
33 33 3 3 3 3 3 33 3 3 3|3 3 3 3:

4 4 4 4 4 4 4 4 4 4 4 4 4 4 4| 1 4 4 I 144444|4444444<|4444444|4444444444444444444444444444444 4 l 4

DIGIT
555555555555555 5|555 i 55
5 5 51 5 5 5 51 5 5 5 5 5 5 5 5| 5 5 5 5 5 5 51 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 PUNCHES

6 E G 6 6 6 G 6 6 6 6 6 E 6 6 6 E | B 6 6 6 6 I,56b666|86666666|6666666|6666666S68666|666666666666666

j j ) 7 7 j 7 7 7 ; 7 7 7 7 7 7 7 7 1 J J; 7 7 7 7 7 7 7 J 7 1 7 7 7 7 7 7 7 7 1 7 7 7 7 7 7 7 1 7 ) 7 7 7 7 J 7 7 1 1 7 7 7 7 7 7 7 7 7 7 J 7 7 7 7 7 J

! 8 8 8 » 3 E ! 3 t 3 3 S 8 8 8 S 8 6 | 8 8 8 3 8 8 8 8 8 ' 3 1 1 8 8 8 8 8 I S 8 1 8 ! 8 1 8 8 ! | J 8 8 I 8 8 1 1 1 1 1 1 ! M I ! ! ! 6 5 8 I 8 It I

9 9 9 'i 9 9 9 9 9 9 5 9 9 5 9 9 9 31 9 9 I 9 9 9 9 9 5 9 9 9 9 9 9 | 9 9 9 9 9 9 3 9 1 9 9 9 3 9 3 3 I « 1 " 3 1 1 3 9 1 1 i 1 "%'I 9 5 9 9 i « 9 i C M ?

FIGURE 1-7 (a) ASCII punched paper tape; (b) Hollerith punched card.

ADDING AND SUBTRACTING BINARY, INPUTS OUTPUTS


OCTAL, HEX, AND BCD NUMBERS
A B CIN ^ CoUT
The previous section of this chapter reviewed common
number systems and codes used with computers. This 0 0 0 0 0
section reviews how to do computations in the previ-
0 0 1 1 0
ously describednumber systems.
0 1 0 1 0
Binary
0 1 1 0 1
ADDITION 1 0
1 0 0
Figure l-8a shows the truth table for addition of two
1 0 1 0 1
binary digits and carry in (C!N| from addition of previous
digits. Figure l-8b shows the result of adding two 8-bit 1 1 0 0 1
binary numbers together using these rules. Assuming
1 1 1 1 1
that Cim =1,1+0 + C|N = a sum of 0 and a carry into
the next digit, and 1 + 1 + C,N = a sum of 1 and a carry
S - A © B © Cm
into the next digit because the result in any digit posi-
tion can
only be a one or a zero. Cut = A %B + C,N [A © B)

2's COMPLEMENT BINARY

2's complement binary is a way of representing negative 10011010


numbers in binary. When you handwrite a number
11011100
which represents some physical quantity such as tem-
perature,
canyousimply put a + sign in front of the m 01110110
number when you wish to indicate that the number is t_, Carry
positive. You can write a - sign when you wish to indi-
cate that
the number is negative. If however, you want
to store values such as temperatures, which can be posi-
tive negative
or in a computer memory, there is a prob- FIGURE 1-8 Binary addition, (a) Truth table for 2 bits
lem. Sincethe computer memory can only store Is or plus carry, (b) Addition of two 8-bit words.

10 CHAPTER ONE
lis. some way must be established to represenl the sign %13 00001101
ol the number with .1 1 oi a 0 + 9 00001001
I he waj to 1In 1Ins is to reserve the mosl significant t22 00010110
bit oi the data word .is ,1 sign bit and to use the resl ol
Sign bit is 0
the bits ol the data word to represenl the size (magni so result is positive
tude) ot the quantity. A computer thai works with 8 bil
(a)
words will use the MSB tbit 7) as the siiju hit and the
lowei seven bits to represenl the magnitude for the t 13 00001101
numbers. The usual convention is to represenl a posi-
- 9 11110111 2's complement for 9 with sign bit
tive number with a o sign bil and a negative number
with a 1 sign bit.
f 4 1J 00000100
1 Sign bit is 0
To make computations with signed numbers easier,
so result is positive
tin- magnitude ol negative numbers is represented m a
Ignore carry
special form called 2's complement. The 2's complement
(b)
ol a binary number is formed by inverting each bit ol the
data word and adding one to (he result. Some examples
+ 9 00001001
should help clarify all of this.
-13 11110011 2's complement lor 13 with sign bit
The number ' 7,,, is represented 1118-bil sign-and-
magnitude form as 0000 0111. The sign bit is zero, - 4 11111100 Sign bit is 1

which indicates a positive number. The magnitude of 0000001 1 So invert each bit

positive numbers is represented in straight binary, so 1 Add 1


equals
0000 01 1 1 in the least-significant bits represents 7,,,. 00000100 Prefix with minus sign
1
To represent -7K, in 8-bit 2's complement sign-and-
(C)
magnitude form, start with the 8-bit code for +7. 0000
0111. Invert each bit to get 1111 1000. Then add 1 to
get 1111 1001. This result is the correct representation
- 9 11110111 I 2's complement,
-13 11110011 | sign-and-magnitude form
of -7i0. Figure 1-9 shows some more examples of posi-
tive andnegative numbers expressed in 8-bit sign-and- 22 11101010 Sign bit is 1
magnitude form. For practice, try generating each of 00010101 So invert each bit
these yourself to see if you get the same result as shown. 1 Add 1
equals
To reverse the above procedure and find the magni- -00010110 Prefix with minus sign
tudeaof number expressed in sign-and-magnitude (cO
form, proceed as follows. 11 the number is positive, as
indicated by the sign bit being a 0. then the least-signif- FIGURE 1-10 Addition of signed binary numbers

icant
bits7 represent the magnitude directly in binary. (a) +() and 1 I % !.(b) 9 and ' I 1. (t 1 +9 and I I

If the number is negative, as indicated by the sign bit id) -') and -13.

being a 1. then the magnitude is expressed in 2's com-


plement.
get the
To magnitude of this negative number
expressed in standard binary, invert each bit of the data Figure 1-10 shows some examples of addition of
word, including the sign bit and add one to the result. signed binary numbers of this type. Sign bits are added
For example, given the word 1110 1011, invert each bit together just as the other bits are. Figure 1 -10a shows
to get 0001 0100. Then add 1 to get 0001 0101. This the results of adding two positive numbers. The sign bit
equals 21 ,0 so you know that the original numbers rep- of the result is zero, so the result is positive. The second
resent10.-21Again, try reconverting a few of the num- example, in Figure 1 - 1Ob, adds a -9 to a +13 or, in
bersFigure
in 1-9 for practice. effect, subtracts 9 from 13. As indicated by the zero sign
bit, the result of this. 4. is positive and in true binary
form.
Sign bit Figure l-10c shows the result of adding a -13 to a
1 : smaller positive number. +9. The sign bit of the result is
+ 7 0 0000111
a 1. This indicates that the result is negative and the
+ 46 0 0101110 magnitude is in 2's complement form. To reconvert a 2's
complement result to a signed number in true binary
+ 105 0 1101001
form :
- 12 1 1110100
1. Invert each bit. to produce l's complement.
- 54 1 100 10 1(J > Sign and
2. Add one.
two's complement
-117 1 0001011
of magnitude 3. Put a minus sign in front to indicate that the result
- 46 1 1010010 is negative.

FIGURE 1-9 Positive and negative numbers represented The final example in Figure l-10d shows the results of
with a sign bit and 2's complement. adding two negative numbers. The sign bit of the result

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES 11


01111111 +127 you like number patterns, you might notice that this
scheme shifts the normal codes for 128 to 255 down-
wardrepresent
to -128 to -1.
If a computer is storing signed numbers as 16-bit
00000001 +1 words, then a much larger range of numbers can be rep-
00000000 ZERO resented.16
Since
bits gives 2lb or 65.536 possible val-
11111111 -1 ues, the
range for 16-bit sign-and-magnitude numbers
is -32,768 to +32,767. Operations with 16-bit sign-
and-magnitude numbers are done the same as was
demonstrated above for 8-bit sign-and-magnitude num-
10000001 -127
bers.
10000000 -128

FIGURE 1-11 Range of signed numbers that can be BINARY SUBTRACTION

represented with 8 binary bits. There are two common methods for doing binary sub-
traction. These
are the pencil method and the 2's com-
plementmethod.
add Figure l-12a shows the truth
is a 1. and the result is negative and in 2's complement table for binary subtraction of two binary digits A and B.
form. Again, inverting each bit. adding 1. and prefixing Also included in the truth table is the effect of a borrow
a minus sign will put the result in a more recognizable in, B|N. from subtracting previous digits. Figure l-12b
form. shows an example of the "pencil" method of subtracting
Now let's consider the range of numbers that can be two 8-bit numbers. Using the truth table, this method is
represented with eight bits in sign-and-magnitude done the same way that you do decimal subtraction.
form. Eight bits can represent a maximum of 2s or 256 A second method of performing binary subtraction is
numbers. Since we are representing both positive and by adding the 2's complement representation of the bot-
negative numbers, half of this range will be positive and tom number(subtrahend) to the top number (minu-
half negative. Therefore, the range then is () to • 127 end). Figurel-12c shows how this is done. First repre-
and from 1 to 128. Figure 1-1 1 shows the sign-and- sent the
top number in sign-and-magnitude form. Then
magnitude binary representations for these values. It form the 2's complement sign-and-magnitude represen-

INPUTS OUTPUTS

A B BIN D B0ut 10101010


01100100
0 0 0 0 0
01000110
0 0 1 1 1

0 1 0 1 1

91,0 01011011 01011011


0 1 1 0 1

-46,0 —00101 110 -^ -> +11010010


1 0 0 1 0 Invert /
45,0 each bit | [Jj 00101101 =45,
1 0 1 0 0
One's comp V,. 11010001 . >, A
1— Indicates
1 1 0 0 0
result positive
Add 1 + ' and in true
1 1 1 1 1
Two's comp
11010010 -'
binary form
Different = A ® B ® Bm Carry
Borrow A %8 + (A © B) %B..

01001101 01001101
38,o 01011000 Complement + 10101000 Complement
00001010
^. 10100111
Qj] 11110101
Add one v 1
Indicates
1011
result negative
Two's comp 10101000 and in two's
Carry complement form

FIGURE 1-12 Binary subtraction, (a) Truth table for 1 bits and borrow, (b) Pencil
method. (C) 2's complement positive result, id) 2's complement negative result.

12 ( MAI' 1 1 K ONI
tation for the negative ol the bottom number. Flnallj 01100 Quotient
.hUI the two parts formed For the example In Figure
I- 12c, the sign of the result Is a zero which Indicates the
Divisor 110)1001000 Dividend 1.'
6)72
resull is posihvt' and in true form. The final carry pro 110
(lined by the addition can be ignored. Figure I 12d 110

shows another example ol ibis method ol subtraction 110

In this ease the bottom number is larger than the top


number. Again, represenl the top number in si^n and
magnitude form, produce the 2's complement sign and
magnitude form for the negative ol the bottom number,
and add the two together. The sign l>ii of the resull is a 110.01 6 25
I for tins example. This indicates that the result is neg-
(III) 11001 00 4)25 00
ative and Ms magnitude is represented in 2's comple-
ineiii form, lb o<i the resull into a form thai is more -100
recognizable to you, invert each bit ol the result, add I
100
to it. and put a minus sii;n in lionl ol it as shown in
Figure l-12d. 100
The examples shown use eight bits, hut the process
01 00
works for any number ol hits. This method may seem
awkward, but it is easy to do in a computer or micro- (b)
processor because
it requires only the simple operations
of inverting and adding. FIGURE I-I4 Binary division.

BINARY MULTIPLICATION

There are several methods of doing binary multiplica- nets arc added as they are produced and the sum ol the
tion. Figure1-13 shows what is called the pencil method partial products is shifted right rather than each partial
because it is the same as the way you learned to multiply product being shifted left.
decimal numbers. The top number or multiplicand is A point to note about multiplying numbers is the
multiplied by the least-significant digit of the bottom number of bits the product requires. For example, mul-
number or multiplier. The partial product is written tiplying
4-bit
two numbers can give a product with as
down. The top number is multiplied by the next disj.il ol many as 8 bits, and two 8-bit numbers can give a 16-bit
the multiplier. The resultant partial product is written product.
down under the last, but shifted one place to the left.
Adding all the partial products gives the total product. BINARY DIVISION
This method works well when doing multiplication by
Binary division can also be performed in several ways
hand, but it is not practical lor a computer because the
Figure 1-14 shows two examples of the pencil method.
type of shifts required make it awkward to implement.
This is the same process as decimal long division. How-
One of the multiplication methods used by computers
ever,
is itmuch simpler than decimal long division be-
is repeated addition. To multiply 7 %55. for example,
causedibits
the of the result (quotient) can only be 0 or
the computer can just add up seven 55's. For large num-
1. A division is attempted on part of the dividend. If this
bers, however,this method is slow. To multiply 786 x
is not possible because the divisor is larger than that
253. for example, requires 252 add operations
part of the dividend, a 0 is entered into the quotient.
Most computers use an add-and-shift-right method.
Another attempt is then made to divide using one more
This method takes advantage of the fact that, for binary
digit of the dividend. When a division is possible, a 1 is
multiplication, the partial product can only be either the
entered in the quotient. The divisor is then subtracted
top number exactly if the multiplier digit is a 1. or a 0 if
from the portion of the dividend used. The process is
the multiplier digit is a 0. The method does tin same
continued as with standard long division until all the
thing as the pencil method except that the partial prod-
dividend is used. As shown in Figure l-14b. O's can be
added to the right of the binary point and division con-
tinued
convert
to a remainder to a binary equivalent.
11 1011 Multiplicand Another method of division that is easier for com-

x 9 1001 puters and


microprocessors to perform uses successive
Multiplier
subtractions. The divisor is subtracted from the divi-
99 1011 '
dend and
from each successive remainder until a bor-
0000 rowproduced.
is The desired quotient is I less than the
% Partial produ number of subtractions needed to produce a borrow.
0000
This method is simple, but lor large numbers it is slow
1011 For faster division of large numbers, computers use a
subtract-and-shift-left method that is essentially the
1100011 Product
same process you go through with a pencil Ion;; divi
FIGURE 1-13 Binary multiplication. sion.

COMPUTER NUMBER SYSTEMS, CODES, AND DICITAl DEVK Is 13


Carry the sum is 16 or greater. An A in hex is a 10 in decimal
1 and an F is 15 in decimal. These add to give 25, which is

100 111 '4/ a carry with a remainder of 9. The 9 is written down and
47e
the carry is added to the next digit column. Then 7 plus
t3G:; + 011 110 + 368 3 plus a carry gives a decimal 1 1 , or B in hex.
1 000 101 8,o 13K, You may use whichever method seems easier to you
and gives you consistently right answers. If you are
1 0 58 1 0 5„
doing a great deal of octal or hexadecimal arithmetic you
(a) (b) might buy an electronic calculator specifically designed
to do decimal, octal, and hexadecimal arithmetic.
FIGURE 1-15 Octal addition, (a) Adding binary
equivalents, (b) Direct octal addition. OCTAL SUBTRACTION

Octal subtraction is shown in Figure 1-17. Since the


least-significant digit of the top number is smaller than
Octal and Hexadecimal Addition and
the least-significant digit of the bottom number, a bor-
Subtraction
row must be done. In octal subtraction. 8 is borrowed
People working with computers or microprocessors from the next digit position and added to the top num-
often use octal or hexadecimal as a shorthand way of ber. Thebottom number is then subtracted and the
representing long binary numbers such as memory ad- remainder written down. The process is continued until
dresses.
is therefore
It useful to be able to add and sub- all digits are subtracted. If you are uncomfortable "bor-
tract octal
and hexadecimal numbers. rowing B's.'you
can just convert the number to decimal,
subtract, and convert the result back to octal.
OCTAL ADDITION

Figure 1-15 shows two ways of adding the octal num-


34
bersand
47 36. The first way is to convert both numbers
to their binary equivalents. Remember, each octal digit -17.
represents three binary digits. These binary numbers 15
are then added using the rules for binary addition from
Figure l-8a. The resultant binary sum is then converted FIGURE 1-17 Octal subtraction.
back to octal.
The second method works directly with the octal form:
7 added to 6 gives 13. which is a carry to the next digit HEXADECIMAL SUBTRACTION
and a remainder of 5. The 5 is written down and the Hexadecimal subtraction is similar to octal subtraction
carry added to the next digit column. Then 4 plus 3 plus except that, when a borrow is needed, 16 is borrowed
a carry gives 8. which is a carry with no remainder. The from the next-most-significant digit. Figure 1-18 shows
0 is written down and the carry is added to the next digit this. It may help you to follow the example if you do par-
column. This is the same process you use for decimal tial conversions to decimal in your head. For example. 7
addition but a carry is produced any time the sum is 8 plus a borrowed 16 is 23. Subtracting B or 1 1 leaves 12
or greater, rather than 10. or C in hexadecimal. Then 3 from the 6 left after a bor-
row leaves3. so the result is 3CH.
HEXADECIMAL ADDITION

As shown in Figure 1-16 the same approaches can be


used to add two hexadecimal numbers. For converting
7716 119,o
to binary, remember that each hex digit represents four -3B„ 5910
binary digits. The binary numbers are added and the
3C,6 60,0
result is converted back to hexadecimal.
The second method works directly with the hex num- FIGURE 1-18 Hexadecimal subtraction.
bers. With
hex addition, a carry is produced whenever

BCD Addition and Subtraction


Carry
| In systems where the final result of a calculation is to be
displayed, such as a calculator, it may be easier to work
1A 0111 1010 7 ' A,t
with numbers in a BCD format. These codes, as shown
+ 3F + 0011 1111 t 3 f,fi in Table 1-1. represent each decimal digit. 0 through 9,
69 1011 1001 with a 4-bit binary word. The BCD words are the same
11,0 25„,
as the binary equivalents for 0 through 9.
5,6 9,6
BCD ADDITION

BCD can have no digit-word with a value greater than 9.


IIGUKI I-I6 Hexadecimal addition. Therefore, a cany must be generated if the result of a

!4 CHAPTER ONE
BCD addition is greatei than loni or 9. Figure l 19 17 1 0111
shows three examples ol BCD addition. The first, In Fig
0 1001
urc l-19a, is very straightforward because the sum is
less than 9. rhe resull is the same as il would be foi 8 i HID Illegal BCD
si. inil. ii d Inn. ii \ 110 Subtract 6
leu the second example, In Figure I 19b, adding BCD
1000 8,,
7 in BCD 5 produces I 100. This is ,i correcl binary re
suli nl 12 bin il is an Illegal BCD code. Io converl Ihe IGURI I .Ml IK 1) m 11111, 11 (ion
resull io BCD format, .i correction factor ol 6 is added.
The rcsuli ol adding 6 is 0001 0010, which is the legal
BCD rude for 12.
BCD SUBTRACTION
Figure l-19c shows anothei case where .i correction
factoi must be added The initial addition ol 9 and 8 Figure 1 20 shows a subtraction <>i B< Dli (0001 01 1 1)
produces 0001 0001. Even though the lower lour digits minus BCD 9 (0000 1001). The initial result, 1 0
are less than 9, this is an incorrecl BOD resull because a 1110. is not a legal BCD number. Whenever this occurs
carry out of bit 3 of the BCD digit-word was produced. ill BCD sill ill, id ion. 0 must he subtracted from Ihe ini-
Tins carry out ol hit 3 is often called an auxiliary cany. tial resull Io produce Ihe correct BCD result. For the
Adding the correction factor of 6 gives the correct BCD example shown in Figure 1-20, subtracting 0 gives a
result of 0001 0111 or 17. correct BCD resull ol 0000 100(1 or 8.
To summarize, a correction factor of 6 must be added The correction factor of 0 must he subtracted from
to the result if the resull in the lower 4 bits is greatei any BCD digit-word il that digit-word is greater than
than 9 or if the initial addition produces a carry out of IO0I . or if a borrow from the next higher digil occurred
bit 3 of any BCD digit-word. This correction is some- during the subtraction.
times called
,i decimal adjust operation.
The reason lor the correction factor of 6 is that in BCD
we want a carry into the next digit after 1001 or 9. but in
binary a cany out of the lower four bits does not occur BASIC LOGIC GATES
until after 1111 or 15. which is 6 more than 9.
Microcomputers such as those we discuss throughoul
this book often contain basic logic gates as "glue" be-
BCD
tween(large
LSI scale integration) devices. For trouble-
35 0011 0101
shootingsystems
these it is important to be able to pre-
+ 23 -t 0010 0011 dict logic
levels at any point directly from Ihe schematic,
rather than having to work your way through a truth
58 0101 1000
table for each gate. This section should help refresh
( a) your memory of basic logic functions and help you re-
memberto how
quickly analyze logic gale circuits.
BCD
7 0111
Inverting and Non-inverting Buffers
+ 5 t 0101
Figure 1-21 shows the schematic symbols and truth
12 1100 Incorrect BCD tables for simple buffers and logic gates. The first tiling
to remember about these symbols is that the shape of
+ 110 Add 6
the symbol indicates the logic function performed by the
0U0 100 If) Correct BCD 12 device. The second thing Io remember about these sym-
bolsthat
is a bubble or no bubble indicates the asser-
(6)
tion level
for an input or output signal. Let's review how
modern logic designers use these symbols.
BCD The first symbol lor a buffer in Figure l-21a has no
1001 bubbles on the input or output. Therefore, the input is
+ 8
active high and the output is active high. We read this
+ 1000
symbol as follows. If the input. A. is asserted high, then
17 00010001 Incorrect BCD the output. Y, will be asserted high. The rest of the truth
110 Add 6 table is covered by the assumption that if the A input is
not asserted high, then the Y output will not be asserted
00010111 Correct BCD 17 high.
The next two symbols lor a hi i Her each contain a huh
(c)
ble. the bubble on the output of the first of these indi-
FIGURE 1-19 BCD addition, la) No correction needed. cates thatthe output is active low. The input has no
(b) Correction needed because of illegal BCD result. bubble so it is active high. You can read the function of
(c) Correction needed because of carry out of BCD the device directly from the schematic symbol as follows.
digit. If the A input is asserted high, then the Y output will be

COMPUTER NUMBER SYSTEMS, CODES, AND DICITAf 1)1 VI i is 15


Again bubbles or no bubbles are used to indicate the
assertion level of each input and output. The first AND
A X Y
symbol in Figure 1-2 lb has no bubbles so the inputs
0 0 1
and the output are active high. The output then will be
1 1 0
asserted high if the A input is asserted high AND the B
input is asserted high. The bubble on the output of the
second AND symbol in Figure 1-2 lb indicates that this
device, commonly called a NAND gate, has an active low
output. If the A input is asserted high and the B input is
asserted high, then the Y output will be asserted low.
4 e \ i

;=0* :=x> 1) i) ii 1
Look at the truth table in Figure 1-2 lb to see if you agree
with this.
1) i ii 1
Figure l-21c shows the other two possible cases for
Y = A %B Y = A +B 1 0 0 1
the AND symbol. The first of these has bubbles on the

:=C>' %:n>-< 1 i 1 II
inputs
schematic,
and on the outputs.
you should
If you see this symbol
immediately see that the output
in a

will be asserted low if the A input is asserted low AND


the B input is asserted low. The second AND symbol in
Figure l-21c has no bubble on the output, so the output
4 B V Y will be asserted high if the A AND B inputs are both
(i 0 II i asserted low.
0 1 1 ii A logic symbol with a curved back indicates that the
1 0 1 0 output of the device will be asserted if the A input is
1 1 1 n
asserted OR the B input of the device is asserted. Again
bubbles or no bubbles are used to indicate the assertion
level for inputs and outputs. Note in Figure 1-2 lb and
Figure l-21c that each of the AND symbol forms has an
equivalent OR symbol form. An AND symbol with active
4 fi \ 1 high inputs and an active high output, for example, rep-
II II 1) 1 resents
same
the device la 74LS08 perhaps) as an OR
symbol with active low inputs and an active low output.
3C^* :=E> II

1
I

II
1

1
II

II Use the truth table in Figure 1-2 lb to convince yourself


I I II 1
of this. The bubbled-OR representation tells you that if
one input is asserted low, the output will be low, regard-
lessthe
of state on the other input. As we will show later
in this chapter, this is often a useful way to think of the
FIGURE 1-21 Buffers and logic gates, (a) Buffers.
(b) AND— NAND. (c) OR— NOR. (d) Exclusive OR. operation of an AND gate.
Figure 1-2 Id shows the symbol and truth table for an
exclusive OR gate. The output of this device will be as-
asserted low. This device then simply changes the asser- serted
theif A input is asserted OR if the B input is
tion level
of a signal. The output, Y. will always have a asserted, but the output will not be asserted if both A
logic state which is the complement or inverse of that on AND B are asserted.
the input, so the device is usually referred to as an in- You need to be able to read all of these symbols, be-
verter. cause most
logic designers will use the symbol that best
The second schematic symbol for an inverter in Figure describes the function they want a device to perform in a
1-2 la has the bubble on the input. We draw the symbol particular circuit.
this way when we want to indicate that we are using the
device to change an asserted-low signal to an asserted-
high signal. For example, if we pass the signal CS Latches, Flip-flops, Registers, and Counters
through this device it becomes CS. The symbol tells you
directly that if the input is asserted low. then the output THE D LATCH
will be asserted high. Now let's review how you express A latch is a digital device that stores a one or a zero on
the functions of logic gates using this approach. its output. Figure l-22a shows the schematic symbol
and truth table for a D latch. The device functions as
follows. If the enable input. E. is low, any data present
Logic Gates on the D input will have no effect on the Q or Q outputs.
Figure 1-2 lb shows the symbols and truth tables for This is indicated in the truth table by an A" in the D
simple logic gates. A symbol with a flat back and a round column. If the enable input is high, a high or a low on
front indicates that the device performs the logical AND the D input will be passed to the Q output. In other
function. This means that the output will be asserted if words, the Q output will follow the D input as long as
the A input is asserted AND the B input is asserted. the enable input is high. The Q output will contain the

16 CHAPTER ONE
complement ol the logic state on (.). When the enable The I) Hip nop in Figure I 22b also has direct set IS|
Inpul is made low again, the state on Q al that time will ami reset (R) inputs a ihp Hup is considered set ii its (}
be latched there Anj changes on D will have no effecl on output is :. It is reset if its Q output is a zero. I In
Q until the enable Input is made high again. When the bubbles on the set and reset inputs tell you that these
enable inpui Lines low, then, the state present on I) insi inputs are active low. The truth table I or the I ) nip Hop
before the enable goes low will be stored on the Q out in Figure l 221) Indicates that the set and reset inputs
put. Keep ilus operation In mind as you read about the are asynchoriOUS. This means thai if the set input is
I) flip Hop In the next section. asserted low, the output will be set. regardless ol the
stale on the I) and the clock inputs. Likewise. II the
THI I) imp-hop reset input is asserted low. the Q output Will be reset,
regardless of the state of the D and clock inputs rheXs
The first type o\Jlip-lh>i> to review is the I) type. Figure
in the /' and CK columns ol the truth table remind you
l-22fa shows the schematic symbol and the truth table
that these inputs are "don't cares' it set Ol reset is ,is-
for ,i typical I) flip-flop. Note that this device has a clock
sei led. The condition indicated by the asterisks (*) is a
input. CK, in place of the enable input on the I) latch.
nonstable condition; that is. it will not persist when
Also note the up arrows in the clock column of the truth
reset or clear inputs return to their inacl ive (high) level.
table. These arrows are used to indicate that a one or
zero on the D input will be copied to the Q output at the
instant the clock input goes from low to high. In other THE )K FLIP-FLOP
words, the D flip-Hop takes a snapshot of whatever state Figure l-22c shows the schematic symbol and the truth
is on the D input when the clock goes high, and displays table for a common Ik Hip-Hop such as the 74LS76. The
the photo on the Q output. If the clock input is low, a two data inputs. ) and K make this device more versatile
change on D will have no effect on the output. Likewise. than a D Hip-Hop. The bubble on the clock input of the
if the clock input is high, a change on D will have no symbol and the downward arrows in the truth table in-
effect on the Q output. Contrast this operation with dicate that
the Q and Q outputs will only change when
that of the D latch to make sure you understand the the clock inpul goes from a high to a low. Changes on )
difference between the two devices. or K will have no effect on the output if the clock input is
low or if the clock input is high.
D t Q 0
If | and K are both low when the CK input goes low. the
outputs will remain the same as they were before the
X u QN On
clock edge. This is indicated by QN and QN in the truth
0 i 0 i
table. If ) is low and K is high at the time of the clock
1 l 1 0
edge. Q will become a zero. If | is high and K is low at the
time of the clock edge, Q will become a one. If | and K are
both high at the time of the clock edge, the Q output will
toggle. This means that it will change to the opposite
s R u CK a Q
state of what it was before the clock edge. The Ik Hip-Hop
1 1 1 t 1 0
also has asynchronous set and reset inputs which func-
D Q
1 0 1 n 1
1
tion the
same as those of the D Hip-Hop described previ-
>CK I 1 X II 0N (.',. ously.
1 1 X 1 oN On
II 1 X X t 0 REGISTERS
1 ii X X i) i
Flip-Hops can be used individually or in groups to store
0 v X binary data. A register is a group of D Hip-Hops con-
nected
parallel
in as shown in Figure l-23a. A binary
word applied to the data inputs of this register will be
transferred to the Q outputs when the clock input is
A fl CK Q Q made high. The binary word will remain stored on the Q
1) II 1 1 1 °N °N outputs until a new binary word is applied to the D in-
I.I 1 1 1 0 1 puts and
a low-to-high signal applied to the clock input.
1 0 1 1 1 0 Other circuitry can read the stored binary word from the
1 1 1 1 TOGGLE
Q outputs at any time without changing its value
'CK ,

If the Q output of each Hip-Hop in the register is con-


K _ Q
'
X 1 1 0 0N Qn
nected
the to D input of the next as shown in Figure
\ X 1 1 1 °N 0N
l-23b. then the register will function as a shift registei
X \ II 1 X 1 0
A one applied to the first D input will be shifted to the
1 1 11 X 0 1
%%
first Q output by a clock pulse. The next clock pulse will
shift this one to the output of the second Hip-Hop. Each
additional clock pulse will shift the one to the next Hip-
FIGURE 1-22 Latches and flip-flops, (a) D latch, (b) D Hop in the register. Some shift registers allow you to
flip-flop, (c) |-K flip-flop. load a binary word into the register and shift the loaded

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES 17


— n.
D,
a, — I
0,
iJ ij J

CK> *-

DATA
OUT

FIGURE 1-23 Registers, (a) Simple data storage, (b) Shift register.

word left or right when the register is clocked. As we will table counter functions, so there is no need to go into
show later in this chapter, the ability to shift binary the internal circuitry of the device. If the reset input is
numbers is very useful. asserted, the Q outputs will all be made zeros. After the
reset signal is unasserted, each clock pulse will cause
COUNTERS the binary count on the outputs to be incremented by
one. As shown in Figure l-24b. the count sequence will
Flip-Hops can also be connected in parallel to make
go from 0000 to 1111. If the outputs are at 1111, then
counters. Figure 1-24 shows a schematic symbol and
the next clock pulse will cause the outputs to "roll over"
count sequence for a presettablc 4-bit binary counter.
to 0000 and a carry pulse to be sent out the carry out-
The main point we want to review here is how a preset-
put. This
carry pulse can be used as the clock input tor
another counter.
Now. suppose that we want the counter to start count-
O, O, O, Q„ ing fromsome number other than 0000. We can do this
0 0 0 0 by applying the desired number to the four data inputs
and asserting the load input. For example if we apply a
binary 6, 01 10, to the data inputs and assert the load
> CLOCK input, this value will be transferred to the Q outputs.
D0 After the load signal is unasserted, the next clock signal
will increment the Q outputs to 0111 or 7. Counters
D,
such as this can be connected in series (cascaded! to
D-, 0.
produce counters of any desired number of bits.
D 0

LOAD

RESET ROMs, RAMs, and Buses


CARRY
flic next topics we need to review are the devices which
store large numbers of binary words and how combina-
tionsthese
of devices can be connected together.

ROMs

The term ROM stands for read-only memory. There are


several types of ROM that can be written to. read,
FIGURL 1-24 Four-bit, presettable binary counter. erased, and written to with new data, but the main fea-
1,1)Schematic symbol, (b) Count sequence. ture ROMs
of is that they are nonvolatile. This means

18 CHAPTFK ONt
,\ i mm ss ii

NCI l is

3DRESS
BUS

A ,

1, ",,i 4Q ^M

l< De «,, Dtt D, I), /J, l)„ D, Dh Db DA D3 D-, D, Dn

D0

DATA
BUS

O, i < %º

FIGURE 1-25 ROMs, (a) Schematic symbol, (fa; Connection in parallel.

that the information stored in them is not lost when the lines connect to each device to allow us to address one of
power is removed from them. the 32,768 words in each. A set of parallel lines used to
Figure l-25a shows the schematic symbol of a com- send addresses or data to several devices in this way is
mon ROM. As indicated by the eight data outputs. DO- called a bus. The data outputs of the ROMs are likewise
D7. this ROM stores 8-bit data words. The data outputs connected in parallel so that any one of the ROMs can
are three-state outputs. This means that each output output data on the common data bus. If these ROMs
can be at a logic low state, a logic high state, or a high- had standard two state outputs, a serious problem
impedance, floating state. In the high-impedance state would occur because each device would be trying to out-
an output is essentially disconnected from anything put an
addressed word onto the data bus. The resulting
connected to it. If the CE input of the ROM is not as- argument between data outputs would probably destroy
serted, all
thenof the outputs will be in the high-imped- some of the outputs and give meaningless information
ance state.
Also, most ROMs switch to a lower-power- on the data bus. Since the ROMs have three-state out-
consumption condition if CE is not asserted. If the CE puts, however,we can use external circuitry to make
input is asserted, the device will be powered up. and the sure that only one ROM at a time has its outputs en-
output buffers will be enabled. Therefore, the outputs abled. very
The important principle here is that when-
will be at a normal logic low or logic high state. You will ever several
outputs are connected on a bus. the outputs
soon see why this is important if you don't happen to should all be three-state, and only one set of outputs
remember. should be enabled at a time.
You can think of the binary words stored in the ROM At the beginning of this section we mentioned that
as being in a long, numbered list. The number that cor- some ROMs can be erased and rewritten or repro-
responds
each to stored word is called its address. In grammed with new data. Here's a summary of the differ-
order to get a particular word onto the outputs of the ent types of ROM.
ROM you have to do two things. You have to apply the
Mask-programmed ROM — Programmed during
address of that word to the address inputs, A0-A14, and
manufacture; cannot be altered.
you have to assert the CE input to turn on the outputs.
Incidentally, you can tell the number of binary words PROM — User programs by blowing fuses: cannot be
stored in the ROM by the number of address inputs. The altered except to blow additional fuses.
number of words is equal to 2N where N is the number of
EPROM — Electrically programmable by user: erased
address lines. The device in Figure l-25a has 15 ad-
by shining ultraviolet light on quartz window in
dress lines,A0-A14. so the number of words is 215 or
package.
32.768. In a data sheet this device would be referred to
as a 32K x 8 ROM. This means 32K addresses by 8 bits EEPROM — Electrically programmable by user; erased
per address.
with electrical signals instead of ultraviolet light.
Now. let's see why we want three-state outputs on this
STATIC AND DYNAMIC RAMs
ROM. Suppose that we want to store more than 32K
data words. We can do this by connecting two or more The name RAM stands for random-access memory, but
ROMs in parallel as shown in Figure l-25b. The address since ROMs are also random access, the name probably

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES 19


be refreshed every two milliseconds or so. A device called
a dynamic RAM refresh controller can be used to refresh
a large number of dynamic RAMs in a system. Some
newer dynamic RAM devices contain built-in refresh cir-
cuitry
they
so appear static to external circuitry.

Arithmetic Logic Units


Previous sections of this chapter reviewed ANDing.
ORlng, exclusive ORing. adding, and subtracting of bi-
nary numbers.A device which can perform any of these
functions and others on binary words is an arithmetic
logic unit or ALU. Figure l-27a shows a block diagram
for the 74LS181 which is a 4-bit ALU. This device can
perform any one of 16 logic functions or any one of 16
arithmetic functions on two 4-bit binary words. The
READ/WRITE
function performed on the two words is determined by
CHIP ENABLE the logic level applied to the mode input, M. and by the
4-bit binary code applied to the select inputs, S0-S3.
FIGURE 1-26 RAM schematic symbol.
Figure l-27b shows the truth table for the 74LS181.
In this truth table A represents the 4-bit binary word
applied to the A0-A3 inputs and B represents the 4-bit
should be read-write memory. RAMs are also used to binary word applied to the B0-B3 inputs. F represents
store binary words. A static RAM is essentially a matrix the 4-bit binary word that will be produced on the F0-F3
of nip-flops. Therefore, we can write a new data word in outputs. If the mode input. M. is high, the device will
a RAM location at any time by applying the word to the perform one of 16 logic functions on the two words ap-
flip-flop data inputs and clocking the flip-flops. The pliedtheto A and B inputs. For example, if M is high
stored data word will remain on the flip-flop outputs as and we make S3 high. S2 low. SI high, and SO high, the
long as the power is left on. This type of memory is vola- 4-bit word on the A inputs will be ANDed with the 4-bit
tile because data is lost when the power is turned off. word on the B inputs. The result of this ANDing will ap-
Figure 1-26 shows the schematic symbol for a com- pear the
on F outputs. Each bit of the A word is ANDed
mon RAM.
This RAM has 12 address lines. AO-Atl, so it with the corresponding bit of the B word to produce the
stores 212 14096) binary words. The eight data lines tell result on F. Figure l-27c shows an example of ANDing
you that the RAM stores 8-bit words. When we are read- two words with this device. As you can see in this exam-
ingword
a from the RAM these lines function as out- ple, output
an bit is high only if the corresponding bit is
puts. Whenwe are writing a word to the RAM. these high in both the A word AND in the B word.
lines function as inputs. The chip enable input, CE, is For another example of the operation of the 74LS 181,
used to enable the device for a read or for a write. The suppose that the M input is high. S3 is high, S2 is high,
R/W input will be asserted high if we want to read from S2 is high, and SO is low. According to the truth table the
the RAM or it will be asserted low if we want to write a device will now OR each bit in the A word with the corre-
word to the RAM. Here's how all these lines work for sponding
in the
bit B word and give the result on the
reading from and writing to the device. corresponding F output. Figure l-27c shows the result
To write to the RAM we applyjhe desired address to that will be produced by ORing two 4-bit words. Figure
the address inputs, assert the CE input low to turn on l-27c also shows for your reference the result that would
the device, and assert the R/W input low to tell the RAM be produced by exclusive ORing these two 4-bit words
we want to write to it. We then apply the data word we together.
want to store to the data lines of the RAM for a specified If the M input of the 74LS181 is low, then the device
time. To read a word from the RAM we address the de- will perform one of 16 arithmetic functions on the A and
sired word,assert CE low to turn on the device, and as- B words. Again the result of the operation will be put on
sert R/Whigh to tell the RAM we want to read from it. the F outputs. Several 74LS181s can be cascaded to op-
For a read operation the output buffers on the data lines erate words
on longer than 4 bits. The ripple-carry
will be enabled and the addressed data word will be pres- input. Cn. allows a carry from an operation on previous
ent onthe outputs. words to be included in the current operation. If the Cn
The static RAMs we have just reviewed store binary input is asserted low. then a carry will be added to the
words in a matrix of flip-flops. In dynamic RAMs results of the operation on A and B. For example if the M
(DRAMs). binary l's and 0's are stored as an electrical input is low, S3 is high, S2 is low, SI is low, SO is high,
charge or no charge on a tiny capacitor. Since these tiny and Cn is low, the F outputs will have the sum of A plus B
capacitors take up less space on a chip than a flip-flop plus a carry.
would, a dynamic RAM chip can store many more bits The real importance of an ALU such as the 74LS 18 1 is
than the same size static RAM chip. The disadvantage of that it can be programmed with a binary instruction
dynamic RAMs is that the charge leaks off the tiny ca- applied to its mode and select inputs to perform many
pacitors.
logic
The state stored in each capacitor must different functions on two binary words applied to its

20 CHAPTER ONE
ACTIVE-HIGH DATA
SELECTION
M H M 1 , AMI 1 lir.1l III i >l'l H "%
LOGIC
S3 S2 SI SO FUNCTIONS H (no carry) ( rj 1 (with carry)

L L L L / A F = A F = A PLUS 1
1 L L H ' A i B F = A * B F ~ (4 ) S) PLUS 1
L 1 H L I At; F = A i li Z7 WiS] PLUS 1
1 L II H I (1 F MINUS 1 (2'sCOMPLI F - ZERO
1 H 1 L F = AB F - A PLUS AB f = 4 PLUS4« PLUS 1
L M 1 H F = B F • {A + B) PLUS4S F = (4 + S) PLUS 40 PLUS 1
1 H H L F = A®B F = A MINUSff MINUS 1 f = 4 MINUSS
1 M H H F = AB F - AB MINUS 1 f = AB
M 1 L L r a i /; F = A PLUS AB F = 4 PLUS4S PLUS 1
H L 1 H F = 4©B F = A PLUSS F = 4 PLUS ff PLUS 1
M L M L F = B F= [A +fi) PLUSES F= (4 +B) PLUS 4S PLUS 1
H 1 H H F = AB F = 4flMINUS 1 F = 4S

H M I L F = 1 F = /1 PLUS4 F= 4 PLUS4 PLUS 1


M II 1 II F = A + B f= W +S) PLUS A f = (4 +fi) PLUS 4 PLUS 1
H H H 1 F = A + B F = {A i B) PLUS A F = (4 + S) PLUS 4 PLUS 1
H H H H F = A F = A MINUS 1 f = 4

n I 1 0

^ / F F0
n II 1 0

^3 / F, F0
1 1 1 0

4©e

FIGURE 1-27 Arithmetic logic unit (ALU), (a) Schematic symbol, (fa) Truth table.
(c) Sample AND, OR, XOR operations.

data inpLits. In other words, instead of having to build a Seven-segment display code
different circuit to perform each of these functions, we
Alphanumeric codes: ASCII, BCDIC, EBCDIC.
have one programmable device. We can perform any of
Selectric, Hollerith
the operations that we want in a computer with a se-
quence
simple
of operations such as those of the Parity bit, odd parity, even parity
74LS181. Therefore, an ALU is a very important part of
the microprocessors and microcomputers which we dis- Converting between binary, octal, hexadecimal, BCD
cussthe
in next chapter. Arithmetic with binary, octal, hexadecimal. BCD

BCD decimal adjust operation


CHECKLIST OF IMPORTANT TERMS AND Signed numbers, sign bit
CONCEPTS IN THIS CHAPTER
2's complement sign-and-magnitude form
If you do not remember any of the terms or concepts in
Signal assertion level
this list, use the index to find them in the chapter.
Inverting and noninverting buffers
Binary, bit, nibble, byte, word, double word
Symbols and truth tables for AND, NAND. OR. NOR.
LSB, MSB, LSD, MSD XOR logic gates.
Octal, hexadecimal, standard BCD, Gray code D latch. D flip-flop, Ik nip-flop

COMPUTER NUMBER SYSTEMS,CODES, AND DIGITALDEVICES 21


Register, shift register, binary counter PROM. EPROM, EEPROM

ROM: address lines, data lines, bus lines RAM: static, dynamic
nonvolatile volatile
three-state READ/WRITE input
cascaded outputs ALU
enable input

REVIEW QUESTIONS AND PROBLEMS


1. Convert the following decimal numbers to binary: 11. Express the following decimal numbers in 8-bit
a. 22 sign-and-magnitude form:
b. 76 a. +26

c. 500 b. -7
c. -26
2. Convert the following binary numbers to decimal: d. -125
a. 1011
b. 11010001 12. Show the subtraction, in binary, of the following
c. 1110111001011001 decimal numbers using both the pencil method
and the 2's complement addition method:
3. ('(invert to following numbers to octal:
a. 7-4
a. 110101001 binary b. 37 - 26
b. 1 1 decimal
c. 1 25 - 93
c. 111011101100 binary
13. Show the multiplication of 1001 and 011 by the
4. Convert the following octal numbers to decimal:
pencil method. Do the same for 11010 and 101.
a. 314
b. 74 14. Show the division of 1 100100 by 1010 using the
c. 43 pencil method.

5. Convert to hexadecimal: 15. Perform the indicated operations on the following


a. 53 decimal numbers:
b. 756 decimal a. The octal numbers 27+16

c. 01101100010 binary b. The octal numbers 132-45

d. 1 10000101 1 1 binary c. 3AH + 94H


d. 17AH - 4CH
6. Convert to decimal:
e. 0101 1001 BCD
a. 1)311
+ 0100 0010 BCD
b. 3FEH
c. 44H

7. Convert the following decimal numbers to BCD: 0111 1001 BCD

a. 86 + 0100 1001 BCD

b. 62
c 33
0101 1001 BCD
S. The L key is depressed on an ASCII-encoded key- 0010 0110 BCD
board. What
pattern of 1 's and 0's would you expect
to find on the seven parallel data lines coming from
the keyboard? What pattern would a carriage re- 0110 01 11 BCD
turn, CR,
give? 001 1 1001 BCD

9. Define parity and describe how it is used to detect


.in ii i in ni I ransmitted data.

10. Show addil inn of: 16. For the circuit in Figure 1-28

a. 1001 I , and 101 I , m binary a. Is the Y output active high or active low?
I). 37|0 and 2510 in BCD b. Is the C signal active high or active low?
c. 37H and 25R in octal c. What input conditions on A. B. and C will

(/. 4A1I and 77H cause the Y output to be asserted?

22 CHAPT1K ONI
19. Why do most ROMs and RAMs have three stale out
puts?
20. Using Figure I 27, show the programming "I th<
select and modi- Inputs the 74181 requires to pi i
form the following arithmeti< functions:
a. A i B
I). A MINUS li MINUS I
c. A PLUS li

21. show the output word produced when the follow


ing binary words arc ANDed with each other and
when they aic ORed with each other:
FIGURE 1-28 Circuit for Problem 1-16.
a. 1010 and 01 I I
b. Kill and I 100
17. What is the main difference between .i I) latch and C I 10101 I 1 and 1 1 1000

a I) nip-flop? d. ANDing an 8-bit binary number with 1111


0000 is sometimes referred to as "masking"
IS. I lie National Semiconductor INS8298 is a 65.536-
the lower 4 bits. Why':'
hii l\( )M organized as 8 192 words or bytes "I 8 bits
How many address lines arc required to address
one oi the 8192 bytes?

COMPUTER NUMBER SYSTEMS, CODES, AND DIGITAL DEVICES 23


CHAPTER

Computers, Microcomputers,
and Microprocessors —An
Introduction
We live in a computer oriented society and we are con- parallel lines called buses. The three buses are the ad-
stantly bombardedwith a multitude of terms relating to dress bus.the data bus. and the control bus.
computers. Before getting started with the main flow of
the book we will t ry to clarify some of these terms and to MEMORY
give an overview of computers and computer systems.
The memory section usually consists of a mixture of
RAM and ROM. It may also have magnetic floppy disks,
OBJECTIVES magnetic hard disks, or laser optical disks. Memory has
two purposes. The first purpose is to store the binary
At the conclusion of this chapter you should be able to: codes for the sequence of instructions you want the
computer to carry out. When you write a computer pro-
1. Define the terms: microcomputer, microprocessor, gram, what
you are really doing is just writing a sequen-
hardware, software, firmware, time share, multi- tial list
of instructions for the computer. The second
tasking, distributed
processing, and multiprocess- purpose of the memory is to store the binary-coded data
ing. with which the computer is going to be working. This
2. Describe how a microcomputer fetches and executes data might be the inventory records of a supermarket,
an instruction.
for example.

3. List the registers and other parts in the 8086/8088 INPUT/OUTPUT


execution unit and bus interface unit.
The input/output or I/O section allows the computer to
4. Describe the function of the 8086/8088 queue. take in data from the outside world or send data to the
outside world. Peripherals such as keyboards, video dis-
5. Demonstrate the way in which the 8086/8088 calcu-
play terminals, printers, and modems are connected to
lates memory addresses.
the I/O section. These allow the user and the computer
to communicate with each other. The actual physical
COMPUTERS devices used to interface the computer buses to external
systems are often called ports. Ports in a computer func-
What is a Computer? tion justas shipping ports do for a country. An input
Figure 2-1 shows a block diagram for a simple com- port allows data from a keyboard, an analog-to-digital
puter. The
major parts are the central processing unit (ADI converter, or some other source to be read into the
or CPU. memory, and the input and output circuitry or computer under control of the CPU. An output port is
I O. Connecting these parts together are three sets of used to send data from the computer to some peripheral

INPUT
DEVICE
I
CONTROL CENTRAL CONTROL
1 0 BUS BUS MEMORY
PROCESSING
PORTS UNIT
(RAM AND
ROM)
(CPUI
OUTPUT
DEVICE '

ADDRESS BUS

I K ,1 IR[ J- 1 Bloi k diagrams ol a simple computer or microcomputer.

24
such as a video display terminal, a printer, 01 .1 digital HARDWARE, SOFTWARE, AND FIRMWARI
to-analog il ' A) 1onvertei Physically, an input 01 outpul When working around computers you hear the terms
port is often just .1 set ol parallel l> Hip Hops which let hardware, software, and firmware almost constantly.
data pass through when they arc enabled or clocked by a Hardware is the name given to the physical devices and
control signal from the CPU. * in iiiiiv ol the computer. Software refers 10 the pro-
grams written
foi the computer. Firmware is the term
CENTRAL PROCESSING UNIT
given i<> programs stored in ROMs or in oilier devices
riic central processing unit or CPU controls the opera which keep theii stored Information when the power is
tion of (lie computer, li fetches binary coded instruc- turned nil
tions from
memory, decodes the instructions into a se
1 irs 0! simple actions, and carries out these actions. The Execution of a Three-Instruction Program
CPU contains an arithmetic logic unit, or ALU. which
can perform add, subtract. OR, AND. invert, or exclu EXECUTION SEQUENCE
sue t )R operations on binary words when instructed to
do so. The CPU also contains an address countei which To line you a better idea ol how the pai is 1ii .; i omputer
function together, we will now describe the aiiions .1
is used to hold the address ol the next instruction or
data to be fetched from memory, general-purpose regis- simple computer might go through to tarn- out [exe
ters whichare used for temporary storage of binary data, cute) .1 simple program. The three instructions of the
and circuitry which generates the control bus signals. program are:

ADDRESS BUS 1. Input a value from a keyboard connected to tin- port


at address 051 1.
The address bus consists of 16. 20. 24. or more parallel
signal lines. On these lines the CPU sends out the ad- 2. Add 7 to the value read in.
dressthe
of memory location that is to be written to or
3. Output the result to a display connected to the port
read from. The number of memory locations that the
at address 02H.
CPU can address is determined by the number of ad-
dress lines.If the CPU has N address lines then it can
Figure 2-2a shows in diagram form the actions that the
directly address 2 to the N power memory locations. For
computer will perform to execute these three instruc-
example, a CPU with 16 address lines can address 2"' or
tions.
65.536 memory locations, a CPU with 20 address lines
For this example assume that the CPU fetches in-
can address 220 or 1.048.576 locations, and a CPU with
structions
dataand from memory one byte at a lime.
24 address lines can address 224 or 16.777,216 loca-
Also assume that the binary codes for the instructions
tions. When
the CPU reads data from or writes data to a
are in sequential memory locations starting at address
port, the port address is also sent out on the address
00100H. Figure 2-2b shows the binary codes that would
bus.
be required in successive memory locations to execute
DATA BUS this program on an 8086- or 8088-based microcom-
puter.
The data bus consists of 8. 16. 32 or more parallel sig- The first action a computer will do is to fetch the first
nal lines. As indicated by the double-ended arrows on instruction byte from memory. To do this the CPU sends
the data bus line in Figure 2-1. the data bus lines are out the address of trie first instruction byte, in this case
bidirectional. This means that the CPU can read data in 00100H, to memory. This action is represented by line
on these lines from memory or from a port as well as 1A in Figure 2-2a. The CPU then sends out a memory'
send data out on these lines to a memory location or to a read signal on the control bus (line IB in the figure).
port. Many devices in a system will have their outputs This causes the memory to output the first instruction
connected to the data bus. but the outputs of only one byte (E4HI on the data bus as represented by line 1C.
device at a time will be enabled. Any device outputs con- The CPU reads in the byte from the data bus and de-
nected
theon data bus must be three-state so that they codesByit. decode we mean that the CPU determines
can be floated when the device is not in use. from the binary code read in what actions it is supposed
to take. In this case the CPU determines that the code
CONTROL BUS read in represents an input instruction. Also from de-
The control bus consists of 4-10 parallel signal lines. coding instruction
this byte, the CPU determines that it
The CPU sends out signals on the control bus to enable needs more information before it can carry out the in-
the outputs of addressed memory devices or port de- struction.
CPUThe must fetch from memory the input
vices. Typical
control bus signals are memory read, port address. To do this the CPU sends out the next se-
memory write. I/O read, and I/O write. To read a byte of quential address
(00101H) to memory as indicated by
data from a memory location, for example, the CPU line 2A in the figure. The CPU also sends out another
sends out the address of the desired byte on the address memory read signal on the control bus (line 2B). This
bus and then sends out a memory read signal on the enables the memory' to put the addressed byte on the
control bus. The memory read signal enables the ad- data bus (line 2C). When the CPU reads in this second
dressed memory
device to output the byte of data onto byte. 05H in this case, it has all the information it needs
the data bus where it is read by the CPU. to execute the instruction.

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS— AN INTRODUCTION 25


FIGURE 2-2 (a) Execution of a three-step computer
program, (b) Memory addresses and memory contents
for a three-step program.

6A 5A 4A 3A 2A 1A IB 2B 3B 4B 5B 1C 2C 3C 4C 5C 6C
i i i i i i
L CONTROL BUS J
3 on
m 3

£ CPU <
s <
<

r CONTROL

1
BUS

1 n
6D 2D 2E 6F

\ I
L
I/O

PORT 05

PROGRAM '

: 6
1. Input a value from port 05. •

2. Add 7 to this value.


3. Output the result to port 01

SEQUENCE

1A CPU sends out address of first instruction to memory.


IB CPU sends out memory read control signal to enable memory.
1C Instruction byte sent from memory to CPU on data bus.
2A Address next memory location to get rest of instruction.
2B Send memory read control signal to enable memory.
2C Port address byte sent from memory to CPU on data bus.
2D CPU sends out port address on address bus.
2E CPU sends out input read control signal to enable port.
2F Data from port sent to CPU on data bus.
3A CPU sends address of next instruction to memory.
3B CPU sends memory read control signal to enable memory.
3C Instruction byte from memory sent to CPU on data bus.
4A CPU sends next address to memory to get rest of instruction.
4B CPU sends memory read control signal to enable memory.
4C Number 07H sent from memory to CPU on data bus.
5A CPU sends address of next instruction to memory.
5B CPU sends memory read control signal to enable memory.
5C Instruction byte from memory sent to CPU on data bus.
6A CPU sends out next address to get rest of instruction.
6B CPU sends out memory read control signal to enable memory.
6C Port address byte sent from memory to CPU on data bus.
6D CPU sends out port address on address bus.
6E CPU sends out data to port on data bus.
6F CPU sends out output write signal to enable port.

26 CHAPTER TWO
AEMi >R> CONTENTS CONTENTS ( )PI RATION
\DDRESS (BINARY) illl X)

001001 I 1 1 10(1100 L4 INPU1 FROM


00101H ooooolol 0r) POR1 05H
00102H 0000010(1 04 Al )l )
00103H 000(101 11 0 0711

00104H 1 1 100 MO E6 outpui ro


0010 -1 1 000000 10 02 P( )KI 02

To execute the inpul instruction the ('I'll sends oul vice so


the dala from the data bus lines can pass
the pent address (05H) on (he address bus (line 2D\ and through i(. When the CPU removes the I/O write signal
sends oul an 1 ( ) read si una 1 on (lie eon I ml bus Mine 2EI. to proceed with the next instruction, the data output
The addressed port device (hen puis a byte of data on will remain latched on the output pins of the porl de-
the data bus (line 2F). The CPU reads in the byte of data vice. Therefore,the computer does not have to keep oul
and stores it in an internal register called the accumu- putting a value in order for it to remain there.
lator. This
completes the first instruction. All of the steps described above may seem like a great
Having completed the first instruction, the CPU must deal of work just to input a value from a keyboard, add 7
now fetch its next instruction from memory. To do this to it. and output the result to a display. Even a simple
it sends out the next sequential address (00102H) on computer, however, can run through all these steps in a
the address bus (line 3A). The CPU then sends out a few microseconds.
memory read signal on the control bus (line 3B). This
allows the memory to put the addressed byte (04H) on SUMMARY OF SIMPLE COMPUTER OPERATION
the data bus (line 3C). The CPU reads in the instruction 1. A simple computer CPU fetches instructions or
byte from the data bus and decodes it. From the instruc- reads data from memory (reads memory) by sending
tion byte
the CPU determines that it is supposed to add out an address on the address bus and a memory
some number to the number stored in the accumulator. read signal on the control bus. The addressed in-
The CPU also determines from this instruction byte that struction
data oris sent from memory to the CPU on
it must go to memory again to get the number that it is
the data bus.
supposed to add. To get the required byte, the CPU will
send out the next sequential address (00103H1 on the 2. The CPU can write data in RAM by sending out an
address bus (line 4A] and a memory read signal on the address on the address bus, sending out the data to

control bus (line 4B). The memory will then put the con- be written on the data bus. and sending out a mem-
tentsthe
of addressed byte (in this case the number ory write signal on the control bus.
07H) on the data bus (line 4C). The CPU will read in the
3. To read data from a port, the CPU sends the port
byte on the data bus and add it to the contents of
address out on the address bus and sends an I/O
the accumulator as instructed. Assume the result of the read signal on the control bus. Data from the port
addition is left in the accumulator. This completes the
comes into the CPU on the data bus.
second instruction.
The CPU must now fetch its next instruction. To do 4. To write data to a port, the CPU sends out the port
this it sends out the next sequential address (00104H) address on the address bus, sends the data to be
on the address bus (line 5A). sends out a memory read written to the port out on the data bus, and sends
signal on the control bus (line 5B). and reads in the ad- an I/O write signal out on the control bus.
dressed (E6H)
byte from the data bus (line 5C). From
5. A microcomputer fetches each program instruction
this byte the CPU determines that it is now supposed to
in sequence, decodes the instruction, and executes
do an output operation to a port. The CPU also deter-
mines that
it must go to memory again to get the ad- it.
dress
theof port that it is supposed to output to. To do
this it sends out the next sequential address (00105H)
Types of Computers
on the address bus (line 6A), sends out a memory read
signal on the control bus (line 6B). and reads in the byte
MAINFRAMES
(02HI put on the data bus by the memory (line 6C\. The
CPU now has all the information that it needs to execute Computers come in a wide variety of sizes and capabili-
the instruction. To output a data byte to a port, the CPU ties. The
largest and most powerful are often called
first sends out the address of the desired port on the mainframes. Mainframe computers may fill an entire
address bus (line 6D), Next it puts the data byte from the room. They are designed to work at very high speeds
accumulator onto the data bus (line 6E). The CPU then with large data words, typically 64 bits or greater, and
sends out an I/O write signal on the control bus (line they have massive amounts of memory. Computers of
6F1. This signal enables the addressed output port de- this type are used for military defense control, business

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS— AN INTRODUCTION 27


business data processing, industrial control (an oil re-
finery,
example),
for and scientific research. Examples
of this type of computer are the Digital Equipment Corp.
VAX 1 1/730 and the Data General MV/8000II. Figure
2-35 shows a photograph of a Digital Equipment Corp.
VAX 1 1/730 minicomputer.
MICROCOMPUTERS

As the name implies, microcomputers are small com-


puters. They
range from small controllers that work di-
rectly with
4-bit words and can address a few thousand
bytes of memory to larger units that work directly with
32-bit words and can address millions or billions of
bytes of memory. Some of the more powerful microcom-
puters have
all or most of the features of earlier mini-
computers. Therefore,
it has become very hard to draw a
sharp line between these two types. One distinguishing
feature of a microcomputer is that the CPU is usually a
single integrated circuit called a microprocessor. Older
books often used the terms microprocessor and micro-
computer interchangeably, but actually the micropro-
cessor
the isCPU to which you add ROM. RAM. and ports
to make a microcomputer. A later section in this chapter
discusses the evolution of different types of micropro-
cessors. Microcomputers are used in everything from
smart sewing machines to computer-aided design sys-
tems. Examples of microcomputers are the Intel 8051
single-chip controller; the SDK-86. a single-board com-
puter designkit: the IBM Personal Computer (PC); and
the Apple Macintosh computer. Figure 2-4a shows a
block diagram of the Intel 8051 single-chip microcon-
troller. Figure
2-4b shows the SDK-86 board, and Figure
2-4c shows the IBM PC. The purpose of this book is to
teach you how microprocessors are connected with other
components to build microcomputers, how the micro-
computers
interfaced
are with peripheral components to
build microcomputer systems, and how these systems
are programmed. We use the IBM PC and the SDK-86
as example systems throughout this book. An available
laboratory manual, written to accompany this book,
shows you how to get started using the SDK-86 board
and the IBM PC for assembly language programming.

SUMMARY OF IMPORTANT POINTS SO FAR


FIGURE 2-3 (a) Photograph of IBM mainframe computer. 1. A computer or microcomputer consists of memory, a
(IBM Corp.) (b) Photograph of DEC minicomputer. CPU. and some input/output circuitry.
(Digital Equipment Corp.)
2. These three parts are connected together by the ad-
data processing (an insurance company, for example), dress bus.
the data bus. and the control bus.
and for creating computer graphics displays for science
3. The sequence of instructions, or program, for a
fiction movies. Examples of this type of computer are
computer is stored as binary numbers in successive
the IBM 438 1. the Honeywell DPS8. and the CRAY X-MP/
48. Figure 2-3a shows a photograph of an IBM 4381 memory locations.
mainframe. 4. The CPU fetches an instruction from memory, de-
codes the
instruction to determine what actions
MINICOMPUTERS must be done for the instruction, and carries out

Scaled-down versions of mainframe computers are often these actions.


called minicomputers. The main unit of a minicomputer
5. Three types of computer are mainframes, minicom-
usually fits in a single rack or box. A minicomputer runs
puters,microcomputers.
and
more slowly, works directly with smaller data words
(often :'»2-bit words), and does not have as much mem- 6. The CPU in a microcomputer is called a microproc-
ory aas mainframe. Computers of this type are used for essor

2H CHAPTER TWO
f±± ±±ri


i[ ii
i i i II

wn

COMPUTERIZING AN ELECTRONICS FACTORY-


PROBLEM

Now. suppose that we want to "computerize" an elec-


tronics company.By this we mean that we want to make
computer use available to as many people in the com-
panypossible
as as cheaply as possible. We want the
engineers to have access to a computer which can help
them design circuits. People in the drafting department
should have access to a computer which can be used for
computer-aided drafting. The accounting department
should have access to a computer for doing all of the
financial bookkeeping. The warehouse should have ac-
cessa tocomputer to help with inventory control. The
manufacturing department should have access to a
computer for controlling machines and testing finished
products. The president, vice presidents, and supervi-
sors should have access to a computer to help them with
long range planning. Secretaries should have access to a
computer for word processing. Sales people should have
access to a computer to help them keep track of current
pricing, product availability, and commissions. There
are several ways to provide all the needed computer
power. The next sections discuss some of the ways that
are used to give people access to a computer.
FIGURE 2-4 (a) Block diagram of Intel 8051 single chip
microcomputer. (Intel Corp.) (b) Photograph ot Intel BATCH PROCESSING
SDK-86 board. (Intel Corp.) (c) Photograph ot IBM PC.
(IBM Corp.) In the 1960s the available computers were very large and
were kept in separate air-conditioned rooms. When pro-
grammers wanted
to run their programs, they brought
How Computers and Microcomputers are them to the computer room. Usually the program was in
Used — An Example the form of a batch of punched cards. A computer opera-
The following sections are intended to give you an over- tor wouldthen run the program. A new programming
viewhow
of computers are interfaced with users to do job could not be started until the last one finished.
useful work. These sections should help you understand Therefore, if a large job was being run. there might be a
many of the features designed into current microproces- considerable wait before a programmer could get his or
sors and
where this book is heading her job run. Also, if an error was found when the pro-

COMPUTERS, MICROCOMPUTERS, AND Ml( KOPRl )( ISSORS— AN INTRODUCTION 29


gram ran. the programmer had to punch new cards, and computer can serve many users by dividing its time
either bribe the computer operator or put the corrected among them in small increments. In other words, the
program cards on the bottom of the jobs-to-be-done pile. computer works on user #l's program for perhaps 20
Needless to say. a system of this sort is not acceptable milliseconds, works on user #2's program for 20 milli-
for computerizing our electronics company, because it seconds,works
then on user #3's program for 20 milli-
only serves one user at a time and does not allow easy seconds,so andon until all all the users have had a
back-and-forth interaction between the computer and turn. In a few milliseconds the computer will get back to
the user. user #1 again and repeat the cycle. To each user it will
appear as if he or she has exclusive use of the computer
MULTIPROGRAMMING because the computer processes data as fast as the user
enters it. A time-share system such as this allows sev-
An improvement over the basic batch system is a multi-
eral usersto interact with the computer at the same
programming In system.
this type of system several pro-
time. Each user can get information from or store infor-
gramsputare in the computer's memory at the same mation
the in large memory attached to the computer.
time. The computer runs one programming job until it
Each user can have an inexpensive printer attached to
reaches a point where it needs access to some slow pe-
the terminal or can direct program or data output to a
ripheral device
such as a printer. If the printer is not
high-speed printer attached directly to the computer.
busy, the computer will print out the produced results.
An airline ticket reservation computer might use a
If the printer is busy, the data to be printed is stored on
time-share system such as this to allow users from all
a magnetic disk. The computer can then start another
over the country to access flight information and make
programming job while it waits for the printer to be-
reservations. A time-multiplexed or time-sliced system
come available.When the printer becomes available, the
such as this can also allow a computer to control many
computer can print out the results from the first pro-
machines or processes in a factory. A computer is much
gram, and
then return to the second program. To fur-
faster than the machines or processes. Therefore, it can
ther reducethe burden on the computer, some com-
check and adjust many pressures, temperatures, motor
puters have
separate circuitry that takes care of copying
speeds, etc. before it needs to get back and recheck the
output data from magnetic disks to the printer. Multi-
first one. A system such as this is often called a multi-
programming the
improves
efficiency of the computer
tasking system
because it appears to be doing many
by keeping it busy more of the time, but it still does not
tasks at the same time.
allow the user to easily interact with the computer.
Now let's take another look at our problem of comput-
erizingelectronics
the company. A time-share system
TIME-SHARE AND MULTITASKING SYSTEMS
seems to be a better idea than a batch system or even a
A further improvement in computer access is timeshar- multiprogramming system. We could put a powerful
ing. Figure2-5 shows a block diagram of one type of computer in some central location and run wires from it
time-share system. Several video terminals are con- to video display terminals on users' desks. Each user
nected
the tocomputer through direct wires or through could then run the program needed to do a particular
telephone lines. The terminal can be on the user's desk task. The accountant can run a ledger program, the sec-
or even in the user's home. The rate at which a user retaryrun
can a word processor program, etc. Each user
usually enters data is very slow as compared to the rate can access the computer's large data memory. Inciden-
that a computer can process the data. Therefore, the tally,
large
a collection of data stored in a computer's

MASS COMPUTER
DATA (MAINFRAME
STORAGE OR MINI)

VIDEO VIDEO
PRINTER LOW-COST
VIDEO TERMINAL TERMINAL
VIDEO PRINTER
ERMINAL TERMINAL

FIGURE 2-5 Block diagram of a computer time-share system.

30 CHAPTFR TWO
MA If: I RAMI Hll ,11 Mi I :
STORAGE COMPUTER PRINTER

CONNI l 1 ION II!


PHONE LINE

FLOPPY DISK
DRIVE

%¡ \Q_\Q
PRINTER MICROCOMPUTER

VIDEO TERMINAL VIDEO TERMINAL VIDEO TERMINAL

FIGURE 2-6 Block diagram of distributed processing computer system.

memory is often referred to as a data base. For a small means that a person can do many tasks locally on the
company a system such as this might be adequate. microcomputer without having to use the large com-
However, there are at least two potential problems. puter
all.at Since the microcomputers are connected to
The first potential problem is "What happens if the the large computer with a network, however, a user can
computer is not working?" The answer to this question access the computing power, memory, or other re-
is that everything grinds to a halt. In a situation where sources
the oflarge computer when needed.
people have become dependent upon the computer, not Distributing the processing around to multiple com-
much gets done until the computer is up and running puters
processors
or in a system has several advantages.
again. The old saying about putting all your eggs in one First, if the large computer goes down, the local micro-
basket comes to mind here. computers
continue
can working until they need to ac-
The second potential problem of the simple time cess the
large computer for something. Second, the bur-
share system is saturation. As the number of users in- den on
the large computer is reduced greatly, because
creases,
timetheit takes the computer to do each user's much of the computing is done by the local microcom-
task increases also. Eventually the computer's response puters. Finally,
the distributed processor approach al-
time to each user becomes unreasonably long. People lows system
the designer to use a local microcomputer
get very upset about the time they have to wait. best suited to the task it has to do.

DISTRIBUTED PROCESSING OR COMPUTERIZED ELECTRONICS COMPANY


MULTIPROCESSING OVERVIEW

A partial solution for the two potential problems of a Distributed processing seems to be the best way to go
simple time-share system is to use a distributed proces- about computerizing our electronics factory. Engineers
sor system.Figure 2-6 shows a block diagram for such a can each have a personal computer on their desk. With
system. The system has a powerful central computer this they can use available programs to design and test
with a large memory and a high-speed printer as does circuits. They can access the large computer if they need
the simple time-share system decribed previously. How- data from its memory. Through the telephone lines, the
ever,this
in system each user or group of users has a engineer with a personal computer can access data in
microcomputer instead of simply a video display termi- the memory of other computers all over the world. The
nal.other
In words, each user station is an independent drafting people can have personal computers for simple
functioning microcomputer with a CPU, ROM, RAM, work, or large computer-aided design systems for more
and probably magnetic or optical disk memory'. This complex work. Completed work can be stored in the

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS— AN INTRODUCTION 31


large computer memory. The accounting department quentialdevices.
logic Also, the ability to change the
can use personal computers with spread sheet pro- function of a system by just changing the programming,
grams
workto with financial data kept in the memory of rather than redesigning the hardware, is very appeal-
the large computer. The warehouse supervisor can like- ing.was
It these factors that pushed the evolution of
wise use
a personal computer with an inventory pro- microprocessors.
gramkeep
to personal records and those in the large In 1972 Intel came out with the 8008 which was capa-
computer's memory updated. Corporate officers can ble ofworking with 8-bit words. The 8008, however,

have personal computers tied into the network. They required 20 or more additional devices to form a func-

then can interact with any of the other systems on the tional CPU.
In 1974 Intel announced the 8080, which

network. Sales people can have portable personal com- had a much larger instruction set than the 8008 and
puters they
that can carry with them in the field. They only required two additional devices to form a functional

can communicate with the main computer over the tele- CPU. Also, the 8080 used NMOS transistors, so it oper-
phone lines
using a modem. Secretaries doing word pro- ated muchfaster than the 8008. The 8080 is referred to

cessing
usecanindividual word processing units or per- as a second-generation microprocessor.
sonal computers.Since word processing is not a high Soon after Intel produced the 8080. Motorola came
intensity use for a computer, several video display ter- out with the MC6800, another 8-bit general-purpose
minals
wordfor processing can be connected to a local CPU. The 6800 had the advantage that it required only a
microcomputer, and this local microcomputer can be + 5 V supply rather than the -5 V, +5 V, and +12 V
connected to the large computer through the network. supplies required by the 8080. For several years the
Users can also send messages to each other over the net- 8080 and the 6800 were the top-selling 8-bit microproc-
work. specifics
The of a computer system such as this essors. Some
of their competitors were the MOS Tech-
will obviously depend on the needs of the individual nology 6502
used as the CPU in the Apple II microcom-
company for which the system is designed. puter, and
the Zilog Z80 used as the CPU in the Radio
Shack TRS-80 microcomputer.
SUMMARY AND DIRECTION FROM HERE As designers found more and more applications for
microprocessors, they pressured microprocessor manu-
The main concepts that you should take with you from
facturers
develop
to devices with architectures and fea-
this section are multiprogramming, time-sharing or
tures optimizedfor doing certain types of tasks. In re-
multitasking, and distributed processing or multiproc-
sponse
the toexpressed needs, microprocessors have
essing.
youAswork your way through the rest of this
evolved in three major directions during the last 10
book, keep an overview of the computerized electronics
company in the back of your mind. The goal of this book years.
is to teach you how all the parts of a system such as this
DEDICATED CONTROLLERS
work, how the parts are connected together, and how
the system is programmed at different levels. One direction has been dedicated controllers. These
The first step toward this goal will be a quick look at devices are used to control "smart" machines such as
the different types of microprocessors available. We then microwave ovens, clothes washers, sewing machines,
discuss a specific microprocessor, the Intel 8086. and auto ignition systems, and metal lathes. Texas Instru-
the programming of a microcomputer built around a ments producedmillions of their TMS-1000 family of
member of this microprocessor family, the IBM PC. Next 4-bit microprocessors for this type of application. In
we discuss the hardware connections and timing of this 1976 Intel introduced the 8048. which contains an 8-bit
microcomputer. From there we show how the micro- CPU, RAM. ROM, and some I/O ports all in one 40-pin
computer
interfaced
is to a wide variety of peripheral package. Other manufacturers have followed with simi-
devices. And finally we cycle back to our computerized lar products. These devices are often referred to as
electronics company, the networks it uses, and the sys- microcontrollers. Some currently available devices in
tem programs it requires. this category, the Intel 8051 and the Motorola MC6801.
for example, contain programmable counters, a serial
port (UART) as well as a CPU, ROM, RAM, and parallel
I/O ports. A more recently introduced single-chip
Common Microprocessor Types
microcontroller, the Intel 8096, contains a 16-bit CPU.
MICROPROCESSOR EVOLUTION
ROM, RAM, a UART, ports, timers, and a 10-bit analog-
to-digital converter.
A common way of categorizing microprocessors is by the
number of bits that their ALU can work with at a time.
BIT-SLICE PROCESSORS
In other words, a microprocessor with a 4-bit ALU will
be referred to as a 4-bit microprocessor, regardless of A second direction of microprocessor evolution has been
the number of address lines or the number of data bus bit-slice processors. For some applications general-
lines that it has. The first microprocessor was the Intel purpose CPUs such as the 8080 and 6800 are not fast
4004 produced in 1971. It contained 2300 PMOS tran- enough or their instruction sets are not suitable. For
sistors. The 4004 was a 4-bit device intended to be used these applications several manufacturers produce de-
with some other devices in making a calculator. Some vices which
can be used to build a custom CPU. An ex-
logic designers, however, saw that this device could be ample
theis Advanced Micro Devices 2900 family of
used to replace PC boards full of combinational and se- devices. This family includes 4-bit ALUs, multiplexers.

32 CHAPTER TWO
sequencers, and other parts needed foi custom building M. I hi I hi i. ii v wind'. I in 8086 has ,1 16-bit data bus, so
.1 CPU. The term slice comes from the fact that these ii ran i en I (1. 11, i iii Mi, mi m hi i lata io memory and ports
pails can be connected in parallel u> work with 8 bil either 16 bits or 8 bits at a time The 8086 lias ., '.'n bil
winds. 16 Imi words, or 32 bit words. In other words, a aililnss bus, so il ran address any one ol
designei can add as many slices as needed for a particu- 1,048,576 memory locations. Each ol the 1,048,576
lar application. the designer not only custom designs i .nlilirsscs ol i he 8086 represents a byte wide
ilic hardware oi the CPU, but also custom makes the location. Words will be stored in two conse< utive mem
instruction sel for it using "microcode." orv locations. II (he lirst byte ol a word is ,il an even
address, the 8086 can read the entire wind in one opera
CENERAL-PURPOSI ( PUs lion. II I he I list byte of the word is at an odd address, the
8086 will read the first byte in one operation, and the
The third major direction ol microprocessor evolution
second byte 111 another operation, hater we will discuss
has been toward general-purpose CPUs which give a
this in del ail. the main point here is that if the In si byte
microcomputer most or all of the computing power ol
ol a 16-bit word is at an even address, the 8086 i an read
earlier minicomputers. After Motorola came out with
the word in one opei it Ion
the MC6N00. Intel produced the 8085. an upgrade of the
The Intel 8088 has the same arithmetic logic unit, the
8080 requiring only a +5 V supply. Motorola then pro-
same registers, and the same instruction set as the
ducedMC6809
the which has a few 16-bit instructions,
8086. The 8088 also has a 20-bit address bus so it can
but is still basically an 8-bit processor. In 1978 Intel
address any one of 1,048,576 bytes in memory. The
came out with the 8086 which is a full 16-bit processor.
8088, however, has an 8-bit data bus so it can only read
Some 16-bit microprocessors, such as the National
data from or write data to memory and ports 8 bits at a
PACE and the Texas Instruments 9900 family of devices,
time. The 8086, remember, can read or write either 8 or
were available previously, but the market apparently
16 bits at a time. To read a 16-bit word from two succes-
wasn't ready. Soon after Intel came out with the 8086.
sive memory locations, the 8088 will always have to do
Motorola came out with the 16-bit MC68000, and the
two read operations. Since the 8086 and the 8088 are
16-bit race was off and running. The 8086 and the
almost identical, any reference we make to the 8086 in
68000 work directly with 16-bit words instead of with
the rest of the book will also pertain to the 808K unless
8-bit words, they can address a million or more bytes of
we specifically indicate otherwise. This is done to make
memory instead of the 64 Kbytes addressable by the
reading easier. The Intel 8088. incidentally, is used as
8-bit processors, and they execute instructions much
the CPU in the IBM Personal Computer and several com-
faster than the 8-bit processors. Also these 16-bit proc-
patible personalcomputers.
essors have
single instructions for functions that re-
The Intel 80186 is an improved version of the 8086.
quired
lengthy
a sequence of instructions on the 8-bit
and the 80188 is an improved version of the 8088. In
processors. addition to a 16-bit CPU the 80186 and 80188 each have
The evolution along this last path has continued on to programmable peripheral devices integrated in the
32-bit processors that work with giga ( 109) bytes or tera
same package. In a later chapter we will discuss these
(1012) bytes of memory. Examples of these devices are
integrated peripherals. The instruction set of the 80186
the Intel 80386. the Motorola MC68020, and the Na-
and the 80188 is a superset of the instruction set of the
tional 32032. 8086. The term superset means that all of the 8086 and
Since we could not possibly describe in this book the
8088 instructions will execute properly on an 80186 or
operation and programming of even a few of the avail-
on an 80188. but the 80186 and the 80188 have a few
able processors,we confine our discussions to primarily
additional instructions. In other words, a program writ-
one group of related microprocessors. The family we
ten loran 8086 or for an 8088 is upward-compatible to
have chosen is the Intel 8086. 8088, 80186. 80188,
an 80186 or to an 80188, but a program written for an
80286 family. Members of this family are very widely
80186 or for an 80188 may not execute correctly on an
used in personal computers, business computer sys-
8086 or an 8088. In the instruction set descriptions in
tems, and
industrial control systems. Our experience
Chapter 6. we specifically indicate which instructions
has shown that learning the programming and opera-
only work with the 80186 or 80188. The 80186 is used
tionone
of family of microcomputers very thoroughly is
as the CPU in several personal computers.
much more useful than looking at many processors su-
The Intel 80286 is an advanced version of the 8086
perficially.
you learnIf one processor family well, you will
specifically designed for use as the CPU in a multiuser or
most likely find it quite easy to learn another when you
multitasking microcomputer. Programs written for an
have to.
8086 can be run on an 80286 operating in its real ad-
dress mode.
We discuss in Chapter 14 the operation
THE 8086, 8088, 80186, 80188, AND and use of the 80286. The 80286 is the CPU used in the
80286 MICROPROCESSORS- IBM PC/AT personal computer.

INTRODUCTION
The Intel 8086 is a 16-bit microprocessor intended to be 8086 INTERNAL ARCHITECTURE
used as the CPU in a microcomputer. The term "16-bit"
means that its arithmetic logic unit, internal registers. The three-instruction program section of this chapter
and most of its instructions are designed to work with describes how a CPU sends out addresses, sends out

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS— AN INTRODUCTION 33


FIGURE 2-7 8086 internal block diagram. (Intel Corp.)

control signals, reads in instructions and data to inter- which does not require use of the buses. When the EU is
nal registers, and sends out data to ports or memory. ready for its next instruction, it simply reads the in-
Before we can talk about how to write programs for the struction
thefrom
queue in the BIU. This is much faster
8086. we need to discuss its specific internal features than sending out an address to the system memory and
such as registers, instruction byte queue, and flags. waiting for memory to send back the next instruction
As shown by the block diagram in Figure 2-7, the 8086 byte or bytes. The process is analogous to the way a
CPU is divided into two independent functional parts, bricklayer's assistant fetches bricks ahead of time and
the bus interface unit or BIU. and the execution unit or keeps a queue of bricks lined up so that the bricklayer
EU. Dividing the work between these two units speeds can just reach out and grab a brick when necessary.
up processing. Except in the cases of |UMP and CALL instructions
where the queue must be dumped and then reloaded
starting from a new address, this prefetch-and-queue
The Bus Interface Unit scheme greatly speeds up processing. Fetching the next
The BIU sends out addresses, fetches instructions from instruction while the current instruction executes is
memory, reads data from ports and memory, and writes called pipelining.
data to ports and memory. In other words the BIU han-
dles all
transfers of data and addresses on the buses for SEGMENT REGISTERS
the execution unit. The following sections describe the The BIU contains four 16-bit segment registers. They
functional parts of the BIU. are: the code segment (CS) register, the stack segment
(SS) register, the extra segment (ES) register, and the
data segment IDS) register. These segment registers are
THE QUEUE used to hold the upper 16 bits of the starting addresses
To speed up program execution, the BIU fetches as many of four memory segments that the 8086 is working with
as six instruction bytes ahead of time from memory. The at a particular time. The 8086 BIU sends out 20-bit ad-
prefetched instruction bytes are held for the EU in a dresses,
it can
so address any of 220 or 1.048.576 bytes
first-in-first-out group of registers called a queue. The in memory. However, at any given time the 8086 only
BIU can be fetching instruction bytes while the EU is works with four. 65.536-byte (64 Kbyte) segments
decoding an instruction or executing an instruction within this 1.048,576-byte II Mbyte) range. Figure 2-8

a CHAPTER TWO
PHYSICAL A stack is .i scci urn n! memor) i el aside in sti
ADDRESS
dresses and data while .i subprogram executi
FFFFFH si.uk segment register is used for the upper 16 bits <>i
I II 1 M the starting address foi the program stack. We will dis-
cuss the use ,ind operation ol ,i si, irk in detail later.
1 he extra segment ir^isin and tin data
istei in- used in hold the uppei l<> bits ol the st.uim^
addresses nl two memory segments thai an- used lor
data.
EXTRA SEGMFNT BASE
ES - 7000H
INSTRUCTION POINTER
5FFFFH — TOPOF STACK i
The nexl lea tore lo look a i in i he I ill i is i he instruction
pointei III'] register. As discussed previously, the code
segment register holds the upper 16 bits ol the starting
address ol the segment from which the BIW is fetching
instruction code bytes. The instruction pointer registei
STACK SEGMENT BASE
holds the 16-bit address of Hie next code byte within
SS - 5000H
this code segment. The value con lamed in the IP is often
me i K i. hi i m 'in referred lo as an offset, because iliis value musl be offset
from (added to) the segment base address in CS to pro-
duce therequired 20-bit physical address. Figure 2-9a
shows in diagram form how this works. The CS register
points to the base or start of the current code segment
The IP contains the distance or offset from this base
CODE SEGMENT BASE
CS = 348AH address to the next instruction byte to be fetched. Fig-
ure 2-9bshows how the 16-bit offset in IP is added to the
TOPOF DATA SEGMENT
16-bit segment base address in CS to produce the 20-bit
physical address. Notice that the two 16-bit numbers
are not added directly in line. One way to describe this
process is to say that the contents of the CS register are
shifted left four bit positions before the contents of the
BOTTOM OF DATA SEGMENT IP are added to it. CS contains 348AH. When shifted left
by four bit positions this produces 348A0H as the start-
FIGURE 2-8 One way that four 64 Kbyte segments ing address of the code segment. The offset of 4214H in
might be positioned within 1 Mbyte address space of the IP is added to this base to give a 20-bit physical ad-
808b. dress 38AB4H.
of

shows how these four segments might be positioned in


memory at a given time. The lour segments can be sepa- PHYSICAL ADDRESSES

ratedshown,
as or. lor small programs which do not TOPOF CODE SEGMENT
need all 64 Kbytes in each segment, they can overlap. A 1J89F II

minimum system, for example, might start all four seg-


ments
address
at 00000H.
To repeat then, a segment register is used to hold the
upper 16 bits of the starting address for each of the seg-
ments. code
The segment register, for example, holds CODE B i il
the upper 16 bits of the starting address for the segment 38AB4H
IP 4214H
from which the BIU is currently fetching instruction
code bytes. The BIU always inserts zeros for the lowest CS - 348AH — *— START OF CODE SEGMENT
348A0H
four bits (nibble) of the 20-bit starting address for a seg-
ment.
the If code segment register contains 348AH. lor
example, then the code segment will start at address
348A0H. In other words, a 64 Kbyte segment can be lo-
cated anywherewithin the 1 Mbyte address space, but
the segment will always start at an address with zeros in
I3 4 8 A 0 IMPLIED ZERO

1 .' 1 1
the lowest 4 bits. This constraint was put on the loca-
PH .Ml AL AHURFSS 3 8 A R 1
tionsegments
of so that it is only necessary to store and
manipulate 16-bit numbers when working with the
starting address of a segment. The part of a segment
starting address stored in a segment register is often FIGURE 2-1) Addition of IP to CS to produce physical
called the segment base. address of code byte, (a) Diagram, (b) Computation.

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS— AN INTRODUCTION 35


The 8086 20-bit physical addresses are often repre- nine Hags are used to indicate some condition produced
sented
a segment
in base: offset form rather than in the by an instruction. For example, a flip-flop called the
single number form. For the address of a code byte the carry flag will be set to a one if the addition of two 16-bit
alternative form will be CS:IP. For example, the address binary numbers produces a carry out of the most signif-
constructed in the preceding paragraph. 38AB4H, can icantposition.
bit If no carry out of the MSB is produced
also be represented as 348A:4214. by the addition, then the carry flag will be a zero. The EU
To summarize, then, the CS register contains the then effectively runs up a "flag" to tell you that a carry
upper 16 bits of the starting address of the code seg- was produced.
mentthein 1 Mbyte address range of the 8086. The in- The six conditional Hags in this group are: the carry
struction pointer
register contains a 16-bit offset which flag (CF), the parity flag (PF), the auxiliary carry flag
tells where in that 64 Kbyte code segment the next in- IAF), the zero flag (ZF), the sign flag (SF1. and the over-
struction
willbyte
be fetched from. The actual physical flow fag(OF). The names of these flags should give you
address sent to memory is produced by shifting the con- hints as to what conditions affect them. Certain 8086
tents
theof CS register four bit positions left and adding instructions check these flags to determine which of two
the offset contained in IP. alternative actions should be done in executing the in-
As you will see in later sections, any time the 8086 struction.
accesses memory, the BIU produces the required 20-bit The three remaining Hags in the flag register are used
physical address by shifting the contents of one of the to control certain operations of the processor. These
segment registers left four bit positions and adding to it flags are different from the six conditional flags de-
a displacement or offset. scribed above
in the way they get set or reset. The six
conditional flags are set or reset by the EU on the basis
of the results of some arithmetic or logic operation. The
The Execution Unit control fags are deliberately set or reset with specific
The execution unit of the 8086 tells the BIU where to instructions you put in the program. The three control
fetch instructions or data from, decodes instructions, flags are the trap flag (TF1, which is used for single step-
and executes instructions. The following sections de- ping through a program; the interruptjlag (IF), which is
scribe functional
the parts of the execution unit. used to allow/prohibit the interruption of a program,
and the direction fag (DF). which is used with string
CONTROL CIRCUITRY, INSTRUCTION instructions.
DECODER, AND ALU Later we will discuss in detail the operation and use of
the nine flags.
Now take another look at the 8086 block diagram in Fig-
ure 2-7to see what is contained in the execution unit.
GENERAL-PURPOSE REGISTERS
The EU contains control circuitry which directs internal
operations. A decoder in the EU translates instructions Observe in Figure 2-7 that the EU has eight general pur-
fetched from memory into a series of actions which the pose registerslabeled AH. AL, BH, BL. CH, CL. DH, and
EU carries out. The EU has a 16-bit arithmetic logic unit DL. These registers can be used individually for tempo-
which can add. subtract, AND, OR, XOR, increment, rary storageof 8-bit data. The AL register is also called
decrement, complement, or shift binary numbers. the accumulator. It has some features that the other
general-purpose registers do not have.
FLAG REGISTER
Certain pairs of these general-purpose registers can
A fag is a flip-Hop which indicates some condition pro- be used together to store 16-bit data words. The accept-
ducedtheby execution of an instruction, or controls able registerpairs are AH and AL. BH and BL, CH and
certain operations of the EU. A 16-bit flag register in the CL. and DH and DL. The AH-AL pair is referred to as the
EU contains nine active flags. Figure 2-10 shows the lo- AX register, the BH-BL pair is referred to as the BX reg-
cation
theof nine flags in the flag register. Six of the ister, the
CH-CL pair is referred to as the CX register.

3085 COMPATIBLE FLAGS

15 14 1! 12 11 10 9 ;-; 7 6 5 4 3 2 1 0

U U U OF DF IF TF SF ZF U AF U PF U CF

U= UNDEFINED
L CARRY FLAG - SET BY CARRY OUT OF MSB
PARITY FLAG - SET IF RESULT HAS EVEN PARITY
AUXILIARY CARRY FLAG FOR BCD
ZERO FLAG - SET IF RESULT = 0
SIGN FLAG = MSB OF RESULT
SINGLE STEP TRAP FLAG
INTERRUPT ENABLE FLAG
STRING DIRECTION FLAG
OVERFLOW FLAG

I IGURE 1- Id 8086 tlag register format. (Intel Corp.)

(6 CHAPTER TWO
and the DI1 DL pair is referred to .is the DX regtstei Foi rhe operation and use of the stack will be discussed in
16-bit operations, AX is called the accumulator. detail lain as need arises
lh, 8086 reglstei set is very similai to those ol the
earlier generation 8080 and 8085 microprocessors. Ii OTHER POINTER AND INDEX REGISTERS
was designed tins way so thai the many programs wrl I In addll Km in the stack p tei registei . SP, the EI i con
ten for the 8080 and 8085 could easily be translated to la ins a 16-bil base polntei (BP) register It also contains
run on the 8086 oi the 8088. The advantage ol using a 16-bil source index (SI) registei and a 16-bit destina-
Internal registers for the temporary storage "i data Is tion indexIDli register. These three registers can be
that, since the data is already In the EU, n can be ac used for temporary storage ol data jusl as the gi neral
cessed much more quickly than it could be accessed in purpose registers described above I lowevei . theii mam
external memory. use is to hold the 16 bit offset ol a data word in one ol
the segments. SI. foi example, can be used to hold the
STACK POINTER REGISTER
offset ol a daia word in the data segment The physical
A stack, remember, is a section ol memory set aside In address ol die data in memory will be generated in this
store addresses and data while a subprogram is execut- case by shilling the contents of the data segment regis-
ing. The
8086 allows you to set aside an entire 64 Kbyte ter fourlui positions to the lefl and adding the contents
segment as a stack. The upper 16 bits of the starting of SI to the result. A later section on addressing modes
address for this segment is kept in the stack segment will discuss and show mam- examples of the use ol these
register. The stack pointer (SP) register contains the base and index registers.
16-bit offset from the start of the segment to the mem-
ory location where a word was most recently stored on
the stack. The memory location where a word was most INTRODUCTION TO PROGRAMMING
recently stored is called the top of stack. Figure 2-1 la THE 8086
shows this in diagram form.
The physical address for a stack read or for a stack Programming Languages
write is produced by adding the contents of the stack Now that you have an overview of the 8086 CPU. it is time
pointer register to the segment base address in SS. To to start you thinking about how it is programmed. To
do this the contents of the stack segment register are run a program, a microcomputer must have the pro-
shifted four bit positions left and the contents of SP are gram stored
in binary form in successive memory loca-
added to the shifted result. Figure 2-1 lb shows an ex- tions. There
are three language levels that can be used
ample.5000H
The in SS is shifted left four bit positions to write a program for a microcomputer.
to give 50000H. When FFE0H in the SP is added to this.
the resultant physical address for the top of the stack MACHINE LANGUAGE
will be 5FFE0H. The physical address can be repre- You can write programs as simply a sequence ot the bi-
sented either
as a single number, 5FFE0H, or it can be nary codes
for the instructions you want the microcom-
represented in SS:SP form as 5000:FFE0H. puter
execute.
to The three-instruction program in Fig-
ure 2-2b
is an example. This binary form of the program
is referred to as machine language because it is the
PHYSICAL ADDRESSES form required by the machine. However, it is difficult, if
END OF STACK 5FFFFH not impossible, for a programmer to memorize the thou-
SEGMENT TOP OF STACK sands
binary
of instruction codes for a CPU such as the
5FFE0H 8086. Also, it is very easy for an error to occur when
working with long series of Is and 0's. Using hexadeci-
mal representation lor the binary codes might help
some, but there are still thousands of instruction codes
to cope with.

ASSEMBLY LANGUAGE
START OF STACK SEGMENT
To make programming easier many programmers write
50000 H
programs in assembly language. They then translate
the assembly language program to machine language so
it can be loaded into memory and run. Assembly lan-
guage uses
two-, three-, or four-letter mnemotiics to
h ii 0 ii ii
represent each instruction type. A mnemonic is just a
F t t 0 device to help you remember something. The letters in
PHYSICAL ADDRESS h F r E u an assembly language mnemonic are usually initials or
(TOP OF STACK) a shortened form of the English word(s) for the opera-
tion performedby the instruction. For example, the
mnemonic for subtract is SUB, the mnemonic for exclu-
FIGURE 2-11 Addition of SS and SP to produce physical sive OR
is XOR, and the mnemonic lor the instruction to
address ot top of stack, (a) Diagram, tbi Computation. copy data from one location to another is MOV.

COMPUTERS. MICROCOMPUTERS, AND MICROPROCESSORS— AN INTRODUCTION 37


the destination, however, cannot both be memory loca-
LABEL OP CODE OPERAND COMMENT
FIELD FIELD FIELD FIELD tionsan
in instruction.

ADD AL. 07H ADD CORRECTION FACTOR A later section on 8086 addressing modes will show all
NEXT:
of the ways in which the source of an operand and the
destination of the result can be specified. The point here
FIGURE 2-12 Assembly language program statement
is that the single mnemonic. ADD. together with a spec-
format.
ified source
and a specified destination can represent a
great many 8086 instructions in an easily understanda-
Assembly language statements are usually written in ble form.
a standard form having four fields. Figure 2-12 shows The question that may occur to you at this point is. "If
an assembly language statement with the four fields I write a program in assembly language, how do I get it
indicated. The first field in an assembly language state- translated into machine language which can be loaded
ment
theis label field. A label is a symbol or group of into the microcomputer and executed?" There are two
symbols used to represent an address which is not spe- answers to this question. The first method of doing the
cifically known
at the time the statement is written. translation is by working out the binary- code for each
Labels are usually followed by a colon. Labels are not instruction a bit at a time using the templates given in
required in a statement, they are just inserted where the manufacturer's data books. We will show you how to
they are needed. We will show later many uses of labels. do this in the next chapter. It is a tedious and error-
The opcode field of the instruction contains the mne- prone task. The second method of doing the translation
monicthe
for instruction to be performed. Instruction is with an assembler. An assembler is a program which
mnemonics are sometimes called operation codes or op- can be run on a personal computer or microcomputer
codes. ADD
The mnemonic in the example statement in development system. It reads the assembly language
Figure 2-12 indicates that we want the instruction to do instructions and generates the correct binary code for
an addition. Chapter 6 describes the function of each each. For developing all but the simplest assembly lan-
8086 instruction type and gives the opcodes for each. guage programs,an assembler and other program devel-
The operandfield of the statement contains the data, opment are
tools essential. We will introduce you to
the memory address, the port address, or the name of these program development tools in the next chapter
the register on which the instruction is to be performed. and describe their use throughout the rest of this book.
Operand is just another name for the data item(s) acted
on by an instruction. In the example instruction in Fig- HIGH LEVEL LANGUAGES
ure 2-12there are two operands. AL and 07H. specified Another way of writing a program for a microcomputer
in the operand field. AL represents the AL register, and is with a high level language such as BASIC, FOR-
07H represents the number 07H. This assembly lan- TFiAN. or Pascal. These languages use program state-
guage statementthen says add the number 07H to the ments which are even more English-like than those of
contents of the AL register. By Intel convention the re- assembly language. Each high level statement may rep-
sult the
of addition will be put in the register or the resent many
machine code instructions. An interpreter
memory location specified before the comma in the op- program or a compiler program is used to translate
erand field.
For the example statement in Figure 2-12 higher level language statements to machine codes
then, the result will be left in the AL register. As another which can be loaded into memory and executed. Pro-
example, the assembly language statement. ADD BH. gramsusually
can be written faster in high level lan-
AL, when converted to machine language and run. will guages than
in assembly language because the high
add the contents of the AL register to the contents of the level language works with bigger building blocks. How-
BH register. The results will be left in the BH register. ever, programs written in a high level language and in-
Looking back at the example assembly language state- terpreted
compiled
or execute slower than the same pro-
ment Figure
in 2-12. observe the comment field which grams written in assembly language. Programs that
starts with a semicolon. This field is very important. involve a lot of hardware control, such as robots and
Comments do not become part of the machine language factory control systems, or programs that must run as
program. You write comments in a program to remind quickly as possible are usually best written in assembly
you of the function that this instruction or group of in- language. Programs that manipulate massive amounts
structions performs
in the program. of data, such as insurance company records, are usually
To summarize why we use assembly language, let's best written in a high level language. The decision of
look a little more closely at the assembly language ADD which language to use has recently been made more dif-
statement. The general format of the 8086 ADD instruc- ficult
theby fact that current assemblers allow the use of
tion is: manv high level language features, and the fact that
some current high level languages provide assembly lan-
ADD destination, source
guage features.

The source can be a number written in the instruction,


OUR CHOICE
the contents of a specified register, or the contents of a
memory location. The destination can be a specified Throughout this book we will use mostly assembly lan-
register or a specified memory location. The source and guage because
we will be working very closely with hard-

W CHAP 11
ware Interfacing. Before we start teaching you assembly her that the destination location is spe< Ified In the In
language programming in the nexl chapter, however, struction before the source Also note that the contents
we wanl to give you an introduction to how the 8086 ol AX are |iist i opied In CX, not actually moved. In oilier
.in esses data. words, the previous contents ol < x are written over, hut
the contents of AX are not changed. Foi example, If CX
contains 2A84H and AX contains 4971H before the
How the HOW) Accesses Immediate and Register MOV CX, AX instruction executes, then alter the in-
Data struction executes
CX will contain 4971H and AX will
hi a previous discussion ol the 8086 Bin we described si ill coi i lam 197 1H. You can MOV any 16-bil registei to
how the 8086 ai cesses code bytes using CS and IP. We any l «> bit register, or sou can MOV any 8 hn register to
also described how the 8086 accesses the stack using any 8 hit register. However, you cannot use an instruc-
ss ami SP. Before we can teach you assembly language tion suchas \H)V ( X, AI because this is an attempt to
copy a byte-type operand (Al.l into a word-type destina
programming techniques, we need to discuss some ol
the different ways that an 8086 can access tin- data that
tion (CX). The' byte in AI. would fit in CX. hut the 8086

ii operates on. The different ways that a processor can


would not know which hall ofCX to put it in. II yon try to
access data are referred to as its addressing modes In write an instruction like this and you are using a good
assembly language statements the addressing mode is assembler, the assemblei will tell you that the instruc-
indicated in the instruction. We will use the ,K086 MOV
tion contains a type error. To copy the byte from AL to
instruction to illustrate some ol the 8086 addressing
the high byte ol CX you can use the instruction MOV
CH, AL. The instruction MOV CL, AL will copy the byte
modes.
The MOV instruction has the format: from AL to CL. the low byte of CX.

MOV destination, source How the 8086 Accesses Data in Memory

When executed, this instruction copies a word or a byte OVERVIEW OF MEMORY ADDRESSING MODES
from the specified source location to the specified desti-
The addressing modes described in the following sec-
nation location.
The source can be a number written
tions used
are to specify the location of an operand in
direi tlv in the instruction, a specified register, or a
memory location specified in one of 24 different ways.
memory. A previous section described how the 8086
produces the physical address for instruction codes by
The destination can be a specified register or a memory
location specified in any one of 24 different ways. The
adding an offset in the instruction pointer to the code
source and the destination cannot both be memory loca-
segment base in the CS register. Remember that the
contents of CS are shifted four bit positions left before
tionsanin instruction.
the contents of IP are added. Another previous section
IMMEDIATE ADDRESSING MODE
described how the 8086 accesses stack locations by add-
ing anoffset in the stack pointer register to the stack
Suppose that in a program you need to put the number segment base in the stack segment register. Here again
437BH in the CX register. The MOV CX, 437BH instruc- the contents of the stack segment register are shifted
tion can
be used to do this. WLien it executes, this in- four bit positions left before the contents of the stack
struction
putwall
the immediate hexadecimal number pointer are added.
437BH in the 16-bit CX register. This is referred to as To access data in memory the 8086 must also produce
immediate addressing mode because the number to be a 20-bit physical address. It does this by adding a 16-bit
loaded into the CX register will be put in two memory value called the effective address to one of the four seg-
locations immediately following the code for the MOV ment bases.
The effective address (EA) represents the
instruction. This is similar to the way the port address displacement or offset of the desired operand from the
was put in memory immediately after the code for the segment base. In most cases, any of the segment bases
input instruction in the three-instruction program in can be specified, but the data segment is the one most
Figure 2-2b. often used. Figure 2- 13a shows in graphic form how the
A similar instruction, MOV CL, 48H could be used to
EA is added to the data segment base to point to an
load the 8-bit immediate number 48H into the 8-bit CL operand in memory. Figure 2- 13b shows how the 20-bit
register. You can also write instructions to load an 8-bit
physical address is generated by the BIU. The starting
immediate number into an 8-bit memory location or to
address for the data segment in Figure 2-135 is 20000H
load a 16-bit number into two consecutive memory loca-
so the data segment register will contain 2000H. The
tions, but
we are not yet ready to show you how to spec- BIU shifts the 2000H four bit positions left and adds the
ify these. effective address. 437AH. to the result. The 20-bit physi-
cal addresssent out to memory by the BIU will then be
REGISTER ADDRESSING MODE 2437AH. The physical address can be represented either
Register addressing mode means that a register is the as a single number. 2437AH, or in the segment base:
source of an operand for an instruction. The instruction offset form as 2000:437AH.
MOV CX, AX. for example, copies the contents of the The execution unit calculates the effective address for
16-bit AX register into the 16-bit CX register. Remem- an operand using information you specify in the in-

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS— AN INTRODUCTION 39


struction acopies
word from memory into the BX regis-
PHYSICAL ADDRESSES
ter. Sinceeach memory address of the 8086 represents a
END OF DATA SEGMENT byte of storage, the word must come from two memory
2FFFFH locations. The byte at a displacement of 437AH from the
data segment base will be copied into BL. The contents
of the next higher address, displacement 437BH. will be
copied into the BH register. The 8086 will automatically
access the required number of bytes in memory for a
DATA BYTE given instruction.
2437AH
The previous two examples showed how the direct
EA = 437AH
addressing mode i an be used to specify the soun e ol an
DS 2000H !— START OF DATA SEGMENT
operand. It can also be used to specify the destination of
20000H
an operand. The instruction MOV [437AH], BX. for ex-
ample,copy
will the contents of the BX register to two
memory locations in the data segment. The contents of
BL will be copied to the memory location at a displace-
!% %
0 n ) ii
ment437AH.
of The contents of BH will be copied to the
1 3 / A memory location at a displacement of 437BH.
PHYSICAL ADDRESS 2 4 1 / /\
'.< ill When you are hand-coding progams using direct ad-
dressing
the ni
form shown above, make Mire to put in the
square brai kets to remind you hov\ to code the instrui tion II
FIGURE 2-13 Addition of data segment register and you leave the brackets out of an instruction such as
effective address to produce physical address of data MOVCX, [437AH], you will < ode it as il it were the instru< turn
byte, la) Diagram, lb) Computation. MOV CX, 4J7AH. This will load the immediate number
437AH into ( Y rathei than load a word from memory at a
struct ion. You can tell the EU to use a number in the displacement ol 437AH, Also note thai if you are writing an
instruction as the effective address, to use the contents instrui tion using direc i addressing sue h as this for ,\n assem-
of a specified register as the effective address, or to com- bler, you
must use a form such as MOV BL, DS:BYTE
pute the
effective address by adding a number in the PTR|437AH| to give the assembler all the information it needs.
instruction to the contents of one or two specified regis- As will be shown in the next chapter, when using an assem-
ters. Thefollowing section describes one way you can bler, we
usually use a name to represent the direct address
tell the execution unit to calculate an effective address. rather than the actual numerical offset
In later chapters we show other ways of specifying the
effective address. We also show how the addressing A FEW WORDS ABOUT SEGMENTATION
modes this provides are used to solve some common At this point you may be wondering why Intel designed
programming problems. the 8086 family devices to use memory segmentation.
At least two reasons come to mind. First, by working
DIRECT ADDRESSING MODE with only 64 Kbyte segments of memory at a time, the
For the simplest memory addressing mode the effective 8086 only has to work with 16-bit effective addresses to
address is just an 8- or 16-bit number written directly in access any location in the segment. In other words, be-
the instruction. The instruction MOV CL, [437AH] is an cause
theof segmentation scheme the 8086 only has to
example. The square brackets around the 437AH are manipulate and store 16-bit address components. The
shorthand for "the contents of the memory locationlsl at second reason has to do with the type of microcomputer
a displacement from the segment base of." When exe- in which an 8086 family CPU is likely to be used. A pre-
cuted, this
instruction will copy the contents of the vious section
of this chapter described briefly the opera-
memory location, at a displacement of 437AH from the tionaoftime-share microcomputer system. In a time-
data segment base, into the CL register. The actual 20- share system several users share a CPU. The CPU works
bit physical memory address will be produced by shift- on one user's program for perhaps 20 milliseconds, then
ing the
data segment base in DS four bits left and add- works on the next user's program for 20 milliseconds.
ing theeffective address 437AH to the result. Figure After working 20 milliseconds for each of the other
2- 13b shows how the operation is done. This addressing users, the CPU comes back to working on the first user's
mode is called direct because the displacement of the program again. Each time the CPU switches from one
operand from the segment base is specified directly m user's program to the next it must access a new section
the instruction. The displacement in the instruction of code and new sections of data. Segmentation makes
will be added t<>the data segment base in DS unless you this switching quite easy. Each user's program can be
use a seqment override prefix to tell the BIU to add it to assigned a separate set of logical segments for its code
some other segment base. We will discuss the segment and data. The user's program will contain offsets or dis-
overide prefix later. placements
thesefromsegment bases. To change from
Another example of this addressing mode is the in- one user's program to a second user's program all that
struction BX,
MOV [437AH], When executed, this in- has to be done is to reload the four segment registers

40 I MAIM IK TWO
wiih the segment base addresses assigned u> the set ond Addi ess. data, and I ontrol buses
user's program. In othei words, segmentation makes II
i ontrol bus signals
easy to keep users' programs and data separate from
each other, and segmentation makes ii easy to switch ALU
from one user's program to anothei user's program
Segmentation

Mill
IMPORTANT TERMS AND CONCEPTS Instruction byte queue, pipelining
EROM THIS CHAPTER ES, CS, SS. DS registers, IP register

EU
II yon do noi remember any ol the terms oi concepts in
AX, MX, CX, D.\ registers, flag register
the following list, use the index to find them In the
ALU. SI'. MP. SI. 1)1 registers
chaptei
Machine language
Microcomputer, mici oprocessoi
Assembly language
Hardware, software, firmware Mnemonic, opcode, operand, label, comment,
Time-share Assembler

Multitasking computer system High level language


Distributed processing system Compiler

Multiprocessing Immediate address mode, register address mode.


direct address mode
CPU
Effective address
Memory, RAM. ROM
I/O ports

REVIEW QUESTIONS AND PROBLEMS


Describe the sequence of signals that occurs on the physical address will a code byte be fetched
address bus. the control bus, and the data bus from if the instruction pointer contains
when a computer fetches an instruction. 539CH?

Describe the main advantages of a distributed pro- 8. What physical address is represented by:
cessing computer
system over a simple time-share a. 4370:561EH
system. b. 7A32:0028H

What determines whether a microprocessor is con-


9. What is the advantage of using a CPU register for
sidered
8-bit.
an 16-bit. or 32-bit device?
temporary data storage over using a memory loca-
a. How many address lines does an 8086 have?
b. How many memory addresses does this num-
10. II the stack segment register contains 3000H and
ber of
address lines allow the 8086 to access
the stack pointer register contains 8434H. what is
directly?
the physical address of the top of the stack?
c. At any given time, the 8086 works with four
segments in this address space. How many 11. a. What is the advantage of using assembly lan-
bytes are contained in each segment? guage instead
of writing a program directly in
d. Why was the 8086 designed with this segmen- machine language?
tal ionol the address space? b. Describe the operation an 8086 will perform
What is the main difference between the 8086 and when it executes ADD AX, BX.
the 8088?
12. What types of programs are usually written in as-
a. Describe the function of the 8086 queue. sembly language?
b. How does the queue speed up process opera-
13. Describe the operation that an 8086 will perform
tion?
when it executes each of the following instructions:
a. II the code segment for an 8086 program starts a. MOV BX, 03FFH
at address 70400H. what number will be in the b. MOV AL, ODBH
CS register? c. MOV DH, CL
b. Assuming this same code segment base, what d. MOV BX, AX

COMPUTERS, MICROCOMPUTERS, AND MICROPROCESSORS— AN INTRODUCTION 41


Write the 8086 assembly language statement 16. If the data segment register, DS, contains 4000H.
which will perform the following operations: what physical address will the instruction MOV AL,
a. Load the number 7986H into the BP register. [234BH] read?
b. Copv the BP register contents to the SP regis- ,_ rp , „„„„ ,
17. II the 8086 data segment register contains 7000H.
ter. ° °
„ ., . . r.. .v „. . . ., r.c write the instruction that will copv the contents of
c. Copv the contents ol the AX register to the DS ^r ,, „ „„„„
DL to address 74B2CH.
register.
d. Load the number F3H into the AL register. 18. Describe the difference between the instructions
„. f. Q„„c .. .. , ,. ,, t. MOV AX, 2437H and MOV AX, [2437H].
II the 8086 execution unit calculates an eftective
address of 14A3H and DS contains 7000H. what
physical address will the Bill produce?

42 CHAPTERTWO
CHAPTER

8086 Family Assembly


Language Programming-
Introduction
The last chapter showed you the format for 8086 assem solve. In oilier words, ask yoursell many times, "What do
bly language programs and introduced you to a few 1 really want this program to do?" If you don't do this,
8086 instructions. Developing a program, however, re- you may write a great program that works, but does not
quires more
than just writing down a series of instruc- do what you need it to do. As you think about the prob-
tions. When
you want to build a house, it is a good idea lemisita good idea to write down exactly what you want
to first develop a complete set of plans for the house. the program to do and the order in which you want the
With the plans you can see if the house has the rooms program to do it. At this point you do not write down
you need, if the rooms are efficiently placed, and if the program statements, you just write the operations you
house is structured so that you can easily add on to it if want in general terms. An example for a simple pro-
you have more kids. We have all probably seen examples gramming problem
might be:
of what happens when someone attempts to build a
house by just putting pieces together without a plan. 1. Read temperature from sensor
Likewise, when you write computer programs it is a
2. Add correction factor of +7
good idea to start by developing a detailed plan or out-
line.
good
A outline helps you to break a large and seem- 3. Save result in a memory location
ingly overwhelmingprogramming job down into small
modules which can easily be written, tested, and de- For a program as simple as this, the three actions de-
bugged.more
The time you spend organizing your pro- sired are
very close to the eventual assembly language
gramsless
the time it will take you to write and debug statements. For more complex problems, however, we
them. You should never start writing an assembly lan- develop a more extensive outline before writing the as-
guage program by just writing down instructions! In sembly language
statements. The next section shows
this chapter we show you how to develop assembly lan- you some of the common ways of representing program
guage programs in a systematic way. operations in a program outline.

OBJECTIVES Representing Program Operations


At the conclusion of this chapter you should be able to: The formula or sequence of operations used to solve a
programming problem is often called the algorithm of
1. Write a task list, flowchart, or pseudocode for a sim- the program. The following sections show you several
ple programming problem. ways of representing the algorithm for a program or pro-
gram segment.
2. Write, code or assemble, and run a very simple as-
sembly language
program. SEQUENTIAL TASK LISTS
3. Describe the use of program development tools such Some programmers use just a sequential list of the
as editors, assemblers, linkers, locators, debuggers, tasks such as that in the preceding section to show the
and emulators. algorithm for their programs. To give you a better idea of
this form, we will show another slightly different exam-
4. Properly document assembly language programs.
ple. Suppose that, instead of taking in one data sample
from the temperature sensor, we want to take in a data
PROGRAM DEVELOPMENT STEPS sample every hour for 24 hours, add 7 to each sample,
and put each corrected value in a memory location We
Defining the Problem could write a task list for this problem as:
The first step in writing a program is to think very care-
fully about
the problem that you want the program to I. Read data sample from temperature sensor.

43
2. Add 7 to value read in. FLOWCHARTS

3. Store eorrected value in memory location. If you have done any previous programming in BASIC or
in FORTRAN, you are probably familiar with flowcharts.
4. Wait one hour.
Flowcharts use graphic shapes to represent different
5. Read next sample from temperature sensor. types of program operations. The specific operation de-
sired
written
is in the graphic symbol. Figure 3-1 shows
6. Add 7 to value read in.
some of the common flowchart symbols. Plastic tem-
7. Store eorrected value in next memory location. platesavailable
are to help you draw these symbols if vou
decide to use them for your programs.
Figure 3-2 shows a flowchart for a program to read in
24 data samples from a temperature sensor at 1-hour
intervals, add 7 to each, and store each result in a mem-
ory location. A racetrack-shaped symbol labeled START
97. Read last data sample from temperature sensor. is used to indicate the beginning of the program. A par-
allelogram
used to is represent input or output opera-
98. Add 7 to value read in. tions.
theIn example we use it to indicate reading data
99. Store corrected value in next memory location.
from the temperature sensor. A rectangular box symbol
is used to represent simple operations other than input
and output operations. The box containing "add 7" in
As you can see. this direct form is not a very compact or
Figure 3-2 is an example.
efficient way of representing the operation of the pro-
A rectangular box with double lines at each end is
gram.
more
A efficient way of writing the sequential task
often used to represent a subroutine or procedure that
list for this program is:
will be written separately from the main program. When
a set of operations must be done several times through-
Read a data sample from temperature sensor.
outprogram,
a it is usually more efficient to write the
Add 7 to the value read in. series of operations once as a separate subprogram and
then just use or "call" this subprogram as it is needed.
Store corrected value in memory location. For example, suppose that there are several times in a
Wait one hour. program where you need to compute the square root of a
number. Instead of writing the series of instructions for
24 samples yet? computing a square root each time you need it in the
No, read next sample and process.
program, you can write the instruction sequence once
Yes. done.
as a subprogram and set it aside in some location in
memory. Vou can then call this subprogram each time
The last three lines indicate that we want the program you need to compute a square root. In the flowchart in
to do the read. add. store, and wait operations 24 times. Figure 3-2 we use the double-ended box to indicate that
Carefully written sequential task lists are often quite the "wait 1 hour" operation will be programmed as a
close to the assembly language statements that will im- subroutine. Incidentally, the terms subprogram, sub-
plement them,
so you may find them useful. As you de- routine,procedure
and all have the same meaning.
termine hardware
details, such as port addresses for the Chapter 5 shows how procedures are written and used.
system on which the program is to run. you can add this A diamond-shaped box is used in flowcharts to repre-
information to the appropriate task statement. The next sentdecision
a point or crossroad. Usually it indicates
section show-, you a more graphic way of representing that some condition is to be checked at this point in the
ilu algorithm of a program or program segment. program and. if the condition is found to be true, one set

OFF PAGE CONNECTOR


CONNECTOR
SUB
ROUTINE
| ) /^~\ Q
FIGURE 5-1 Flow, h.iit symbols

44 ( HAPTER lllkl t
f STAR! J however, have several disadvantages First, yo
write much Informal in the little boxes Second,
flowcharts do nol present information In a verj <ompai i
form. For mine complex problems, flowcharts lend to
become spread out over many pages I hej are verj hard
in follow back and forth between pages Ftiird and most
important, with flowcharts the overall structure ol the
program tends to get losl in the details. The following
section describes a more clearly structured and compact
method ol representing the algorithm of a program or
pi ogi .mi segment.

MRU RJRED PROGRAMMING AND


PSEUDOCODE OVERVIEW

In the early days ol computers a single brilliant person


might write even a large program single-handedly. The
main concerns in this case were. "Does the program
work?" and "Whal do we do if this person leaves the
company?" As the number of computers increased and
the complexity of the programs being written increased,
large programming jobs were usually turned over to a
team of programmers. In this case the compatibility of
parts written by different programmers became an im-
portant concern.
During the 1970s it became obvious to
many professional programmers that, in order for team
C STOP J programming to work, a systematic approach and
standardized tools were absolutely necessary.
FIGURE 3-2 Flowchart for program lo read in 24 data One suggested systematic approach is called top-
samples from a port, correct each value, and store each down design. In this approach a large programming
in a memory location. problem is first broken down into major modules. The
top level of the outline shows the relationship and func-
tionthese
of modules. This top level then presents a
of actions is to be done. If the condition is found to be one-page overview of the entire program. Each of the
false, then another set of actions is to be done. In the major modules is broken down into still smaller mod-
example flowchart in Figure 3-2 the condition to be ules following
on pages. The division is continued until
cheeked is whether 24 samples have been read in and the steps in each module are clearly understandable.
processed. If 24 samples have not been read in and proc- Each programmer can then be assigned a module or set
essed, arrow
the labeled NO in the flowchart indicates of modules to write for the program. Also, those who
that we want the computer to jump back and execute want to learn about the program later can start with the
the read. add. store, and wait steps again. If 24 samples overview and work their way down to the level of detail
have been read in. the arrow labeled YES in the flow- they need. This approach is the same as drawing the
chartFigure
of 3-2 indicates that all the desired opera- complete plans for a house before starting to build it.
tions have
been done. The racetrack-shaped symbol at The opposite of top-down design is bottom-up design.
the bottom of the flowchart indicates the end of the pro- In this approach each programmer starts writing low-
gram. level modules and hopes that all the pieces will eventu-
The two additional flowchart symbols in Figure 3-1 ally together.
fit When completed, the result should be
are connectors. If a flowchart column gets to the bottom similar to that produced by the top-down design. Many
of the paper, but all of the program has not been repre- modern programming teams use a combination of the
sented,can
you put a small circle with a letter in it at the two techniques. They do the top-down design and then
bottom of the column. You then start the next column at build, test, and link modules starting from the smallest
the top of the same paper with a small circle containing and working upward.
the same letter. If you need to continue a flowchart to The development of standard programming tools was
another page, you can end the flowchart on the first helped by the discovery that any desired program opera-
page with the five-sided off-page connector symbol con- tion couldbe represented by three basic types of opera-
taining
lettera or number. You then start the flowchart tion. The
first type of operation is sequence which
on the next page with an off-page connector symbol con- means simply doing a series of actions. The second
tainingsame
the letter or number. basic type of operation is decision or selection, which
For
simple programs and program sections, flow- means choosing between two alternative actions. The
charts
a are
graphic way of showing the operational flow third basic type of operation is repetition or iteration.
of the program. We will show flowcharts for many of the which means repeating a series of actions until some
program examples throughout this book. Flowcharts. condition is or is not present.

808b FAMILY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION 45


On the basis of this observation, the suggestion was The WHILE-DO structure in Figure 3-3d is one form
made that all programmers use a set of three to seven of repetition. It is used to indicate that you want to do
standard structures to represent all of the operations in some action or sequence of actions as long as some con-
their programs. Actually, only three structures. dition
present.
is This structure represents a program
SEQUENCE. IF-THEN-ELSE, and WHILE-DO. are loop. The example in Figure 3-3d is:
required to represent any desired program action, but
three or four more structures derived from these often WHILE money lasts DO

make programs clearer. If you have previously written Eat supper out.

programs in a structured language such as Pascal, then Go to movie.

these structures are probably already familiar to you. Take a taxi home.

Figure 3-3 uses flowchart symbols to represent the com-


monly used
structures so you can more easily visualize This example shows a sequence of actions you might do
their operations. In actual program documentation, each evening until you ran out of money. Note that, in
however. English-like statements called pseudocode are this structure, the condition is checked before the
used rather than the space-consuming flowchart sym- action is done the first time. You certainly would want to
bols. Figure
3-3 also shows the pseudocode format and check how much money you have before eating out.
an example for each structure. Another useful structure, derived from the WHILE-
Each structure has only one entry point and one exit DO structure, is the REPEAT-UNTIL structure shown
point. The output of one structure is connected to the in Figure 3-3e. You use this structure to indicate that
input of the next structure. Program execution then you want the program to repeat some action or series of
proceeds through a series of these structures. actions until some condition is present. A good example
Any structure can be used within another. An IF- of the use of this structure is the programming problem
THEN-ELSE structure, for example, can contain a se- we used in the discussion of flowcharts. The example is:
quence
statements.
of Any place that the term state-
ments) appears
in Figure 3-3. one of the other REPEAT
structures could be substituted for it. The term "state- Get data sample from sensor.
ment(s)" can also represent a subprogram or procedure Add correction of +7.
that is called to do a series of actions. Store result in a memory location.
Wait one hour.
STANDARD PROGRAMMING STRUCTURES UNTIL 24 samples taken.

The structure shown in Figure 3-3n is an example of a


simple sequence. In this structure the actions are sim-
Compare the space required by the pseudocode repre-
ply written down in the desired order. An example is:
sentation
the desired
for action with the space required
by the flowchart representation shown in Figure 3-2.
Read temperature from sensor. The space advantage of pseudocode should be obvious.
As indicated previously, the REPEAT-UNTIL struc-
Add correction factor of t-7.
turederived
is from the WHILE-DO. In other words, any
Store corrected value in memory. problem that can be represented by a REPEAT-UNTIL
can also be represented by a properly written WHILE-
Figure 3-3b shows an IF-THEN-ELSE example of the DO. The example in Figure 3-3e could be written as:
decision operation. This structure is used to direct op-
eration
oneto of two different actions based on some WHILE NOT 24 samples DO
condition. An example is: Read data sample from temperature sensor.
Add correction factor of +7.
IF temperature less than 70 degrees THEN Store result in memory location.
Turn on heater Wait one hour.
ELSE
Turn nil heater Note that the REPEAT-UNTIL structure indicates that
the condition is first checked after the statement(s) is
The example says that it the temperature is below the performed. In other words, a REPEAT— UNTIL structure
thermostat setting, we want to turn the heater on. II the indicates that the action or series of actions will always
temperature is equal to or above the lhermcist<it setting, be done at least once. If you don't want this to happen,
we want to turn the heater oil. then use the WHILE— DO which indicates that the con-
The IF-THEN structure shown in Figure 3-3c is the dition
checked
is before any action is taken. As we will
same as the IF-THEN-ELSE except that one of the show later, the structure you use makes a difference in
paths contains no action. An example ol this is: the actual assembly language program you write to im-
plement it.
IF hungry THEN The WHILE-DO and REPEAT-UNTIL structures con-
Get food tainsimple
a IF—THEN-ELSE decision operation. How-
ever, since
this decision is an implied part of these two
I he assumpt ion tor tins example is thai if you are not structures, we don't indicate the decision separately in
hungry, you will just continue on with your next task. them.

46 i M 'NIK THRFt
-r
1 %:
u /

>% -'

-
,' 5 * :% m
I „ ^ (- O O
< tn O * 5-
:. LI.

<

2 -

5>o
- <

z <
LU (J

g 2
5 —- 1
< < --' ~
-
1
Q L_

T
TO

§
C Z
•a 0
X
s
h-
-,-
/

:

OS C
_ i
"5
u
— E

8086 FAMILYASSEMBLY
LANGUAGEPROGRAMMING- INTRODUCTION 47
Another form of the repetition operation that you more complex programming problems, a sequential list
might see in high level language programs is the FOR- may become very messy because it has little real struc-
DO loop.
This structure has the form: ture standardization.
or Another way of representing
program operations is with flowcharts. Flowcharts are a
FOR count = 1 TO n DO very graphic representation, and they are useful for
statement short program segments, especially those that deal di-
statement rectly with
hardware. However, flowcharts use a great
deal of space. Consequently, the flowchart for even a
moderately complex program may take up several pages.
In assembly language we usually implement this type of
It often becomes difficult to follow program flow back
operation with a REPEAT-UNTIL structure, so we have
and forth between pages. Also, since there are no
not included a sample of it.
agreed-upon structures, a poor programmer can write a
The CASE structure shown in Figure 3-3/ is a com-
flowchart which jumps all over the place and is even
pact way
of representing a choice among several alterna-
more difficult to follow. The term "logical spaghetti"
tive actions.The choice is determined by testing some
comes to mind here.
quantity. The example in Figure 3-3/ best shows how
A third way of representing the operations you want
this is used. This everyday example describes the de-
in a program is with a top-down design approach and
sired actions
for a cook in a restaurant. The pseudocode
standard program structures. The overall program
is just a summary of the thinking the cook might go
problem is first broken down into major functional
through. The cook or the computer checks the value of
modules. Each of these modules is broken down into
the variable called "day" and selects the appropriate ac-
smaller and smaller modules until the steps in each
tionsthat
for day. Each of the indicated actions, such as
module are obvious. The algorithms for the whole pro-
"Make celery soup." is itself a sequence of actions which
gram andfor each module are each expressed with a
could be represented by the structures we have de-
standard structure. Only three basic structures.
scribed.
SEQUENCE, IF-THEN-ELSE. and WHILE-DO. are
The CASE structure is really just a compact way to
needed to represent any needed program action or series
represent a complex IF-THEN-ELSE structure. To il-
of actions. However, other useful structures such as IF-
lustrateFigure
this, 3-3g also shows how the soup cook
THEN, REPEAT-UNTIL. FOR-DO. and CASE can be
example can be represented as a series of IF-THEN-
derived from these basic three. A structure can contain
ELSE structures. Note that, in this example, the last
another structure of the same type or one of the other
IF-THEN has no ELSE after it because all of the possible
types. Each structure has only one entry point and one
days have been checked. You can, if you want, add the
exit point. These programing structures may seem re-
final ELSE to the IF-THEN-ELSE chain to send an
strictive,
using
but them usually results in program rep-
error message if the data does not match any of the
resentationsarewhich
easy to understand and for
choices. The CASE structure does contain the final
which it is easy to write the programs. A program writ-
ELSE, however. The CASE form is more compact for
ten ina structured manner is easier to debug and
documentation purposes and some high-level languages
much more understandable to someone else who has to
such as Pascal allow you to implement it directly. How-
work on it. Furthermore, a program representation de-
ever, the
IF-THEN-ELSE structure gives you a much
velopedstructured
with programming techniques can
better idea of how you write an assembly language pro-
be implemented easily in assembly language or in a
gram sectionto choose between several alternative ac-
high-level language such as Modula II or C.
tions.
Throughout the rest of this book we show you how to
use these structures to represent program actions and Finding the Right Instruction
how to implement these structures in assembly lan-
After you get the structure of a program worked out and
guage.
written down, the next step is to determine the instruc-
tion statements required to do each part of the program.
SUMMARY OF PROGRAM STRUCTURE
Since the examples in this book are based on the 8086
REPRESENTATION FORMS
family of microprocessors, now is a good time to give you
Writing a successful program does not consist of just an overview of the instructions the 8086 has for you to
writing down a series of instructions. You must first use.
think carefully about what you want the program to do You do not usually learn a new language by studying
and how you want the program to do it. Then you must its dictionary from cover to cover. It is more productive
represent the structure of the program in some way that to first learn a few very useful words and learn how to
is very clear to you and to anyone else who might have to put together simple sentences. You can then learn more
work on the program. If the structure is well developed, words as you need them to express more complex
it is usually not a difficult step to write the actual pro- thoughts. Chapter 6 contains a dictionary of all of the
gramming language
statements that implement it. 8086 instructions with detailed descriptions and exam-
One way of representing program operations is with a ples for
each. You can use this as a reference as you
sequential lask list. For initial thinking and simple pro- write programs. Here we simply list the 8086 instruc-
gramming problems
this technique works well. For tions
Junctional
in groups with single-sentence descrip-

48 CHAPTER IHKft
lions so thai you can see the types ol Instructions thai SAH1 Store (copy) All registei to low byte ol flag
are available to you. As you read through this set tlon, do registei .
not expect to understand all ol the Instructions. When
PUSHF Copy 11«iLi,register to top ol stack.
you si. u i writing programs, you will probably use ihis
section to determine the type of Instruction and Chapter POPF Copy word at top ol stack to flag registi i
6 to get the Instruction details .is you need them. Aftei
you have written a few programs, you will remember ARITHMI IK INSIRIK IIONS
most oi the basic Instruction types and will be able to
Addition instructions:
|ust look up an instruction in Chapter 6 to get any addl
tional del. ills you need. Chaptei I shows you in detail
ADD Add specified byte to byte, oi specified word
how to use the move, arithmetic, logical, jump, and to word.
string instructions. Chapter 5 shows how to use the call
Instructions and the stack. ADC Add byte * byte • carry flag oi word
As von skmi through the following overview ol the word • (airy flag.
8086 instructions, see II you can find the instructions
INC Increment specified byte or specified word by
needed to do the "read temperature sensor value from a
one.
port, add I 7. and store result in memory" example pro-
gram. AAA ASCII adjust alter addition

DATA TRANSFER INSTRUCTIONS DAA Decimal (BCD) adjust after addition.

General-purpose byte or word transfer instructions:


Subtraction instructions:
MNEMONIC DESCRIPTION
SUB Subtract byte from byte, or word from word.
MOV Copy byte or word from specified source to
specified destination. SBB Subtract byte and carry flag from byte, or
word and carry flag from word.
PUSH Copy specified word to top of stack.
DEC Decrement specified byte or specified word
POP Copy word from top of stack to specified
by one.
location.
NEC Negate— invert each bit of a specified byte or
PUSHA (80186/80188 ONLY) Copy all registers to
word and add 1 (form 2's complement).
stack.
CMP Compare two specified bytes or two specified
POPA (80186/80188 ONLY) Copy words from
words.
stack to all registers.
AAS ASCII adjust after subtraction.
XCHG Exchange bytes or exchange words.
DAS Decimal (BCD) adjust after subtraction.
XLAT Translate a byte in AL using a table in
memory.
Multiplication instructions:
Simple input and output port transfer instructions:
MUL Multiply unsigned byte by byte or unsigned
IN Copy a byte or word from specified port to word by word.
accumulator.
IMUL Multiply signed byte by byte or signed word
OUT Copy a byte or word from accumulator to by word.
specified port. AAM ASCII adjust after multiply.

Special address transfer instructions:


Division instructions:

LEA Load effective address of operand into


DIV Divide unsigned word by byte, or unsigned
specified register.
double word by word.
LDS Load DS register and other specified
IDIV Divide signed word by byte, or signed double
register from memory.
word by word.
LES Load ES register and other specified
AAD ASCII adjust before division.
register from memory.
CBW Fill upper byte of word with copies of sign
Flag transfer instructions: bit of lower byte.

LAHF Load (copy to) AH with the low byte of the CWD Fill upper word of double word with sign bit
of lower word.
flag register.

8086 FAMILY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION 4«)


BIT MANIPULATION INSTRUCTION'S REPNE REPNZ An instruction prefix.
Repeat until CX = 0 or
Logical instructions:
ZF = 1.
NOT Invert each bit of a byte or word. MOVS MOVSB MOVSW Move bvte or word from
one string to another.
AX I J AND each bit in byte or word with the
corresponding bit in another byte or COMPS COMPSB COMPSW Compare two string
word. bytes or two string
i >1< OR each bit in a byte or word with the words.
i orresponding bit in another byte or 1XS IXSB IXSW 180186 80188) Input
word. string byte or word from
XOR Exclusive OR each bit in a byte or word port.
with the corresponding bit in another OUTS OUTSB OUTSW (80186 80188) Output
byte or word. string byte or word to
AND operands to update flags, but don't port.
change operands. SCAS SCASB SCASW Scan a string. Compare
a string bvte with bvte
Shift instructions: in AL or a string word
with word in AX.
SHL SAL Shift bits of word or byte left, put zero(s|
LODS LODSB LODSW Load string byte into AL
in LSB(s).
or string word into AX.
SHR Shift bits of word or byte right, put
STOS STOSB STOSW Store byte from .AL or
zero(s) m MSI
word from AX into
SAR Shift bits of word or byte right, copy old string.
MSB into new MSB.
PROGRAM EXECUTION TRANSFER
Rotate instructions: INSTRUCTIONS

These instructions are used to tell the 8086 to start


ROL Rotate bits ol byte or word left. MSB to
fetching instructions from some new address, rather
LSB and to CF.
than continuing in sequence.
ROR Rotate bits of byte or word right. LSB to
MSB and to CF.' Unconditional transfer instructions:

RCL Rotate bits of byte or word left. MSB to


CALL Call a procedure (subprogram), save return
CF and CF to LSB.
address on stack.
RCR Rotate bits nt byte or word right. LSB to RET Return from procedure to calling program.
CF and CF to MSB.
JMP Go to specified address to get next
instruction.
STRING INSTRUCTIONS

NOTES A string is a series of bytes or a series of Conditional transfer instructions:


words in sequential memory locations. A strum often
\( )TE A " " is used to separate two mnemonics which
consists of ASCII character codes. In the list a " " is
represent the same instruction. Use the mnemonic
used to separate different mnemonics for the same
which most clearly describes the decision condition in a
instruction. Use the mnemonic which most clearlv
specific program. These instructions are often used
describes the function of the instruction in a spe-
after a compare instruction. The terms below and
cific application. A "B" in a mnemonic is used to
a/wre refer to unsigned binary numbers. Above means
specifically indicate that a string of bytes is to be
larger in magnitude. The terms greater than or less
acted upon. A "W" in the mnemonic is used to in-
than refer to signed binary numbers. Greater than
dii ate that a string of words is to be acted upon.
means more positive.
REP An instruction prefix.
JA JXBE Jump if above Jump if not below nor
Repeat following
equal.
instruction until CX =
(i
JAE JNB Jump if above or equal Jump if not
REPEREPZ
below.
An instruction prefix.
Repeat instruction until JB JNAE Jump if below Jump if not above nor
CX = 0 or ZF -%1 equal.

50 CHAPTER THRU
JBE JNA Jump il below or equal Jump il nol INTO Interrupt program execution it overflow
above. flag I.

,ic Jump il carry flag \CV) 1. [RET Return from interrupt service procedure
to main program
JE JZ Jump il equal Jump il zero flag (ZF) I

JG JNLE Jump il greater Jump it nol less than //n//i level language interface instructions
noi equal
ENTER (80186 80188 ( INLY) Enter procedure.
JGE JNL Jump il greater than or equal Jump il
noi less than. I 1. \\i (80186/80188 ONLY) Leave procedure.

HOUND (.sols), 80188 < INLY) cheek il effei tive


JL/JNGE Jump it less than/Jump it nol greater
address within specified array bounds.
i han nor equal.
JLE JNG Jump it less (han or equal Jump it nol PROCESSOR CONTROL INSTRUCTIONS
greatei than
Flag set/clear instructions:
JNC Jump it no carry (Jump il carry lla^
0). STC Set carry Hag (CF) to 1.

JNE.JNZ Jump il not equal/Jump il nol zero (zero CLC ( le.11 carry flag (CF) to 0.
flag = 0).
CMC Complement the state ol the earn' flag [< I
JNO Jump if no overflow (Jump if overflow
STD Set direct ion flag (DPI to 1 (decrement
flag = 0).
string pointers).
JNP/JPO Jump if not parity/Jump it parity odd
CLD Clear direction flati (DF) to 0.
(PF = 0).
STI Set interrupt enable flag to 1 (enable 1NTR
JNS Jump if not sign (Jump it sign flag = 0).
input I.
JO Jump if overflow flag = 1.
CL1 Clear interrupt enable flag to 0 (disable
JP/JPE Jump if parity/Jump if parity even (PF - INTR input).
1).
External hardware synchronization instructions:
JS Jump if sign flag = 1.

Iteration control instructions: HLT Halt (do nothing! until interrupt or reset.

WAIT Wait (do nothing) until signal on the TEST


These instructions can be used to execute a series of
pin is low.
instructions some number of times. Here mnemonics
separated by a "/" represent the same instruction. Use ESC Escape to external coprocessor such as

the one that best fits the specific application. 8087 or 8089.

LOCK An instruction prefix. Prevents another


LOOP Loop through a sequence of processor from taking bus while the
instructions until CX = 0. adjacent instruction executes.
LOOPE/LOOPZ Loop through a sequence of
instructions while zero flag = 1 No operation instruction:
and CX * 0.
NOP No action except fetch and decode.
LOOPNE/LOOPNZ Loop through a sequence of
instructions while zero flag = 0
and CX # 0. Now that you have glanced through an overview of the
JCXZ Jump to specified address if CX 8086 instruction set. let's see if you found the instruc-
tions neededto implement the "read sensor, add +7.
0.
and store result in memory'' example program. The IN
instruction can be used to read the temperature value
If you aren't tired of instructions, continue skimming
through the rest of the list. Don't worry if the explana- from an A/D converter connected to a port. The ADD in-
struction
be can
used to add the correction factor of +7
tionnot
is clear to you because we will explain these
to the value read in. Finally, the MOV instruction can be
instructions in detail in later chapters.
used to copy the result of the addition to a memory loca-
Interrupt instructions: tion.
major
A point here is that breaking the program-
ming problem down into a sequence of steps makes it
INT Interrupt program execution, call service easy to find the instruction or small group of instruc-
procedure. tions that
will perform each step. The next section

8086 FAMIlY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION ^)1


shows you how to write the actual program using these 8259A priority interrupt controller
instructions.
8254 programmable counter
8251 A programmable serial port
Writing a Program Initialize data variables

INITIALIZATION INSTRUCTIONS Reset/clear direction flag and interrupt enable flag


Alter finding the instructions needed to do the main As you can see, the list can become quite lengthy even
part of your program, there are a few additional instruc- though we have not included all of the devices a system
tions youneed to determine before you actually write might commonly have. Note that initializing the code
your program. The purpose of these additional instruc- segment register is absent from this list. The code seg-
tionsto isinitialize various parts of the system such as ment register
gets loaded with the correct starting value
segment registers, flags, and programmable port de- by the system command you use to run the program.
vices. Segment registers, for example, must be loaded Now let's see how you put all of these parts together to
with the upper 16 bits of the address in memory where make a program.
you want the segment to begin. For our "read tempera-
ture sensor,add +7, and store result in memory" exam- A STANDARD PROGRAM FORMAT
ple program, the only part we need to initialize is the
In this section we show you the form your programs
data segment register. The data segment register must
should have if you are going to construct the machine
be initialized so that we can copy the result of the addi-
codes for each instruction by hand. A later section of
tionatolocation in memory. If. for example, we want to
this chapter will show you the additional parts you need
store data in memory starting at address 00100H. then
to add to the program if you are going to use an assem-
we want the data segment register to contain the upper
bler produce
to the binary codes for the instructions.
16 bits of this address, 0010H. The 8086 does not have
To help you format your programs, assembly lan-
an instruction to move a number directly into a segment
guage coding
sheets such as that shown in Figure 3-4
register. Therefore, we move the desired number into
are available. The address column is used for the ad-
one of the 16-bit general-purpose registers, and then
dress
theor offset of a code byte or data byte. The actual
copy it to the desired segment register. Two MOV in-
code bytes or data bytes are put in the data/code col-
structions
do will
this.
umn.
label
A is a name which represents an address
If you are using the stack in your program, then you
referred to in a jump or call instruction. A label is put in
must include an instruction to load the stack pointer
the label column. It is followed by a colon (:| if it is used
register with the offset of the top of the stack. Most mi-
by a jump or call instruction in the same code segment.
crocomputer systems
contain several programmable
The opcode column contains the mnemonics for the
peripheral devices such as ports, timers, and control-
instructions. The operand column contains the regis-
lers. Youmust include instructions which send control
ters, memorylocations, or data acted upon by the in-
words to these devices to tell them the function you
structions.
comment A column gives you space to de-
want them to perform. Also, you usually want to include
scribe the
function of the instruction for future
instructions which set or clear the control flags such as
reference.
the interrupt enable flag and the direction flag.
Figure 3-4 shows how the instructions for the "read
The best way to approach the initialization task is to
temperature, add +7, store result in memory" program
make a checklist of all the registers, programmable de-
can be written in sequence on a coding sheet. We will
vices, flags
and in the system you are working on. Then
discuss here the operation of these instructions to the
you can mark the ones you need for a specific program
extent needed. If you want more information about any
and determine the instructions needed to initialize each
of these, detailed descriptions of the syntax (assembly
part. An initialization list for an 8086-based system,
language grammar) and operation of each of these in-
such as the SDK-86 prototyping board, might look like
structions
be can
found in Chapter 6.
the following.
The first line at the top of coding form in Figure 3-4
does not represent an instruction. It simply indicates
INITIALIZATION LIST that we want to set aside a memory location to store the

Data segment register result. This location must be in available RAM so that
we can write to it. Address 00100H is an available RAM
Stack segment register location on an SDK-86 prototyping board, for example.

Extra segment register Next, we decide where in memory we want to start put-
ting the
code bytes for the instructions of the program.
Stack pointer register Again, on an SDK-86 prototyping board, address
00200H and above is available RAM. so we chose to start
Base pointer register
the program at address 00200H.
Source index register The first operation we want to do in the program is to
initialize the data segment register. As discussed previ-
Destination index register
ously, MOV
two instructions are used to do this. The
8255 programmable ports MOV AX, 0010H instruction, when executed, will load

52 ( HAIMIR IHRU
PROGRAMMER 2> Mill I

PROGRAM TITLE &


,-, : a \oc ...% •:eadi ••: %t •>%%<\oLt %vain % i%ienion. connected %
[acton ol +7 to the value %I • ..... % eittlt ••%.
None coiled.
R£Q!)S7£t%'kSC^. A*
- ., . ,.-.:. utuui ..

1/tiei 05 aA-input pont


MCMOMj. 00/OOJl ^AHA; 00200J4 -0020GJ, G05>£

DATA
ADDRESS 1 ABI 1 S MNEM. OPERAND(S) COMMENTS
or
CODE

!, '•, 'ii XX Qeiemte memonu location to to <

" . :1 leAntt. 'llwi location- uull ae loaded


V utdk a data Lute oA-lead in

00/03 Z connected
luf Ike pnoanam.
00/04 XX meanA- dan t cane amid
00/05 contenti ol location.

00/06

00/07

00/08

00/09

00/OA

00/08

00)00.

00/OD

00/OE Code itanti kene

00/OF Note bleak in addneA-i

200 38 MOV AX. 00/OJf 9ndiaii'ie 2)£ to point to itaAt o[


0\ 10 memoMf,
iet aAide[on.itouna-data
02 00

Oi sS MOV 2>£, AX
04 2>8
OS .:'• M AI, 05Jl Readtempenatune
[nom
Ob 05 pont 05Jl
07 04 A2>2> AZ 07Jl Add connection
[acton
(98 07 o[ +07
09 A2 MOV [oooo], Alt Stale leinlt in leie-Mied

OA 00 .;/. •>:.. :,:

OB 00

OC gg Ml i Stop, utait [on command


00 [namu4en
OE

Of

FIGURE 3-4 Assembly language program on standard coding form.


53
the upper 16 bits of the address we chose for data stor- has shown that even a short program that you wrote a
age into the AX register. The MOV DS, AX instruction month ago and forgot to put comments on may not be at
will copy this number from the AX register to the data all understandable to you now.
segment register. Now we get to the instructions that do
what we started out to do. The IN AL, 05H instruction
will copy a data byte from port 05H to the AL register.
CONSTRUCTING THE MACHINE CODES
The ADD AL, 07 instruction will add 07H to the AL regis-
FOR 8086 INSTRUCTIONS
ter andleave the result in the AL register. The MOV
[0000], AL instruction will copy the byte in AL to a mem- This section shows you how to construct the binary
ory location at a displacement of 0000H from the data codes for 8086 instructions. Most of the time you will
segment base. In other words. AL will be copied to a probably use an assembler do this for you, but it is use-
physical address computed by shifting the data segment ful to
understand how the codes are constructed. If you
base in DS, 001 OH. four bit positions left and adding have an 8086-based prototyping board such as the Intel
the displacement. 0000H. contained in the instruction. SDK-86 available, knowing how to hand-code instruc-
The data will then be copied to physical address 00 100H tions will
enable you to code, enter, and run simple pro-
in memory. This is an example of the direct addressing grams
you
as work your way through the 8086 instruc-
mode described near the end of the previous chapter. tion set
examples in the next chapters.
The INT 3 instruction at the end of the program func-
tionsa asbreakpoint. In most 8086 systems, when the
8086 executes this instruction it will cause the 8086 to
stop executing the instructions of your program and Instruction Templates
return control to the monitor or system program. You To code the instructions for 8-bit processors such as the
can then use system commands to look at the contents 8085. all you have to do is look up the hexadecimal code
of registers and memory locations, or run another pro- for each instruction on a one-page chart. For the 8086
gram. Without an instruction such as this at the end of the process is not quite as simple. Here's why. There are
the program, the 8086 would fetch and execute the code 32 ways to specify the source of the operand in an in-
bytes for your program, and then it would go on fetching structionassuchMOV CX, source. The source of the
meaningless bytes from memory and trying to execute operand can be any one of eight 16-bit registers, or a
them as if they were code bytes. memory location specified by any one of 24 memory ad-
The next major section of this chapter will show you dressing modes.
Each of the 32 possible instructions
how to construct the binary codes for these and other requires a different binary code. If CX is made the
8086 instructions so that you can assemble and run the source rather than the destination then there are 32
programs on a development board such as the SDK-86. ways of specifying the destination. Each of these 32
First, however, we want to use Figure 3-4 to make an possible instructions requires a different binary code.
important point about writing assembly language pro- There are then 64 different codes for MOV instructions
grams. using CX as a source or as a destination. Likewise, an-
othercodes
64 are required to specify all of the possible
MOVs using CL as a source or a destination, and 64
DOCUMENTATION
more are required to specify all of the possible MOVs
In a previous section of this chapter we stressed the using CH as a source or a destination. The point here is
point that you should do a lot of thinking and carefully that, because there is such a large number of possible
write down the algorithm for a program before you start codes for the 8086 instructions, it is impractical to list
writing instruction statements. You should also docu- them all in a simple table. Instead, we use a template for
ment the
program itself so that its operation is clear to each basic instruction type and fill in bits within this
you and to anyone else who needs to understand it. template to indicate the desired addressing mode, data
Each page of the program should contain the name of type, etc. In other words, we build up the instruction
the program, the page number, the name of the pro- codes on a bit-by-bit basis.
grammer,
perhaps
and a version number. Each pro- Different Intel literature shows the code templates for
gramprocedure
or should have a heading block which the 8086 instructions in two slightly different formats.
contains an abstract describing what the program is One format is shown at the end of the 8086 data sheet in
supposed to do, which procedures it calls, which regis- Appendix A. The second format is shown along with the
tersuses,
it which ports it uses, which flags it affects, 8086 instruction timings in Appendix B. We will start by
the memory used, and any other information which will showing you how to use the templates shown in the
make it easier for another programmer to interface with 8086 data sheet. As a first example of how to use these
the program. templates we will build the code for the IN AL, 05H in-
Comments should be used generously to describe the structionourfromexample program. Figure 3-5a shows
specific function of an instruction or group of instruc- the template for this instruction. Note that two bytes are
tions Not
every statement needs an individual com- required for the instruction. The upper 7 bits of the first
iii iii ( omments should not just repeat the instruction byte tell the 8086 that this is an "input from a fixed
mnemonii port'' instruction. The bit labeled W in the template is
We cannot overemphasize the importance of clear. used to tell the 8086 whether you want to input a byte or
concise documentation in your programs. Experience input a word. If you want the 8086 to input a byte from

",4 ( HAI'TIK THREt


i kiii ici.i register. Note ili.ii a I leasl two code bytes are
1 1 I J i equlred for the Insl rui lion
I he uppei (> bils ol the liisi byte are an opcode which
OPCODE FOR "IN"
indicates the general type "I instruction. Look in the
v. n ic i i table in Appendix A i<> find the 6-bil opcode for tins
W 1 WORD M( )V reglstei memory in from register instruction. Win
should find il id In- 1000 10. The W bit in the In si word
is used to indicate whether a byte oi .i word is being
moved. II you are moving a byte, make this bit a 0. II you
1 1 0 0 1 0 0 0 i) 0 0 II 1 0 arc moving .i word, make this bil a I. In ibis instruc
i inn. inn- operand must always be a register, so 3 bits in
OPCODE FOR IN" POR1 05H the second byte are used in indicate which registei is
Involved. The .''>bit codes foi each register are shown at
- INPUT A BYTE
the end oi the table in Appendix A and in Figure 3 7a
Look in one ol these places in find the code for the CL
register. You should gel 001 . The I) bit in the first byte
ADDRESS CONTENTS of the instruction code is used to indicate whether the
nn w.n E4H
data is being moved to the register identified in the Rl C
00206 H IIMI field of the second byte or from that register. II you arc
moving dala to the register identified in the Kid field,
make the D bit a 1. If you are moving data from thai
FIGURI i-">Coding template for 80Kb IN (fixed-port) register, make the D bit a 0.
instruction, (a) Template, (b) Example, (c) Hex (odes in Now remember that in this instruction one operand
sequential memory locations. must be a register. The 2-bit field labeled MOD and the
3-bit field labeled R/M in the second byte of the instruc-
tion code
are used to specify the desired addressing
an 8-bit pint to AL, then make the W bit a 0. If you want mode for the other operand. Figure 3-8 shows the MOD
the 8086 to input a word from a 16-bit port to the AX and R/M bit patterns for each of the 32 possible address-
register, then make the W bit a 1. The 8-bit port ad- ing modes.
dress. 05H
or 00000101 binary, is put in the second If the other operand in the instruction is also one of
byte (if I he instruction. When the program is loaded into the eight registers, then put in 1 1 for the MOD bits in
memory to be run. the first instruction byte will be put the code template. Put the 3-bit code for that register in
in one memory location and the second instruction byte the R/M bits in the code template.
will be put in the next. Figure 3-5c shows this in hexa- For the case where the other operand is a memory lo-
decimalas
formE4H. 05H. cation there
are 24 ways of specifying how the execution
To further illustrate how these templates are used, we unit should compute the effective address of the oper-
will show here several examples with the simple MOV and in
memory. Remember from Chapter 2 that the ef-
instruction. We will then construct the codes for the fective address
can be specified directly in the instruc-
example program in Figure 3-4. Other examples will be tion,can
it be contained in a register, or it can be the
shown as needed in the following chapters. Figure 3-6 sum of one or two registers and a displacement. Figure
shows the coding template or format for 8086 instruc- 3-8 shows the MOD and R/M codes for each of the 24
tions which
MOV data from a register to a register, from ways of specifying an effective address. The MOD code
a register to a memory location, or from a memory loca- indicates whether the address specification in the in-

REGISTER SELECT (SEE FIGURE 3-7)

BYTE 3 BYTE 4

1 | 0 | 0 | 0 | 1| 0 1 1 LOWDISPLACEMENT
j HIGHDISPLACEMENT
OPCODE D w MOD REG R/M
I

DIRECT ADDRESS DIRECT ADDRESS


LOW BYTE HIGH BYTE

• (5 BITS! ADDRESSING MODE (SEE FIGURE 3-8)


BYTE/WORD DATA 0 = BYTE 1 = WORD
DIRECTION TO/FROM REG 0=FROM 1 = TO

OPERATION CODE

FIGURE 3-6 Coding template for 8086 instructions which MOV data between
registers or between a register and a memory location.

8086 FAMILY ASSEMBLY LANGUAGE PROGRAMMING — INTRODUCTION r>.->


REG FIELD BIT ASSIGNMENTS struction contains a displacement. The R/M code indi-
cates which register(s) contain part(s) of the effective
If- W = 1 16-BIT REGISTER address. Here's how it works:

REGISTER CODE I. [f the specified effective address contains no dis-


placement
in theas instruction MOV CX, |BX] or in
AX 000 the instruction MOV [BX][SI], DX. then make the
MOD bits 00. and chose the R/M bits which corre-
r %; 00 1 spond
theto registerls) containing the effective ad-
dress.example,
For if an instruction contains [BX],
the 3-bit R/M code is 111. For an instruction which
DX 0 10
contains [BX)[SI], the R/M code is 000. Note that for
direct addressing where the displacement of the
BX 011
operand from the segment base is specified directly
in the instruction, MOD is 00 and R/M is 110. For
SP 100 an instruction using direct addressing the low byte
of the direct address is put in as a third instruction
BP 101 code byte of the instruction, and the high byte of the
direct address is put in as a fourth instruction code
BI 1 10 byte.

2. II the effective address specified in the instruction


D I 111 contains a displacement less than 256 along with a
reference to the contents of a register, as in the in-
IF W = 0 S-BIT REGISTER struction MOV CX, 43H[BX], then code in MOD as
01, and chose the R/M bits which correspond to the
REG ISTER CODE registerls) which contain the part(s) for the effective
address. For the instruction MOV CX, 43H[BX],
AL 000 MOD will be 01 and R/M will be 111. Put the 8-bit
value of the displacement in as the third byte of the
p. (-)fj, 1 instruction.
3. If the expression for the effective address contains a
DL 010 displacement which is too large to fit in 8 bits, as in
the instruction MOV DX, 4527H[BX], then put in 10
oi 0 1 i for MOD. and chose the R/M bits which correspond
to the registerls! which contain the part(s) for the
effective address. For the instruction MOV DX,
AH 1 00
4527H[BX| the R/M bits are 111. The low byte of the
displacement is put in as a third byte of the instruc-
CH 101.
tion. The
high byte of the displacement is put in as a
fourth byte of the instruction. The examples which
DH 1 10 follow should help clarify all of this for you.

BH 1 1 1
MOV Instruction Coding Examples
All of the examples in this section use the MOV instruc-
..„„,- r-.,^ „„ tion template in Figure 3-6. As you read through these
SbbREG CODE , .. , „ , . . . , t , c .. ." . ,.t
examples, it is a good idea to keep track of the bit-by-bit
development on a separate paper for practice.
ES 00

CODING MOV SP, BX


CS 01
This instruction will copy a word from the BX register to
the SP register. Consulting the table in Appendix A, you
SS 10
find that the 6-bit opcode for this instruction is 100010.
Make the W bit a 1 because you are moving a word. The
DS 1 1
D bit for this instruction may be somewhat confusing,
however. Since two registers are involved, you can think
(ft)
of the move as to SP, or from BX. Actually, it does not
FIGURE 5-7 Instruction codes tor 8086 registers. matter which you assume as long as you are consistent
(a) General purpose, pointers, and index, (b) Segment in coding the rest of the instruction. If you think of the
registers. instruction as moving a word to SP, then make the D bit

56 ( HAPTER IMKII
R M 00 01 in 11

W i) U 1

000 BX ' I [BX] • [SI] • d8 |BX| + |SI| • ilhi

001 |BX| + |l)l| |BX| I |l >l| i d8 [BX] 1 il HI • di6 ( 1 ( X

010 [BP] + [SI] [BP] • [SI] • d8 IBP] I |SI| • d16 1)1 DX

nl 1 IBP] i [Oil |BP] t [01] • do [BP] I |DI] • d16 Bl BX

100 [SI] |SI| ' d8 [SI] • d16 All SP

101 11)11 nil . (I:; |DI| • (IK. (II BP

1 10 (IK. [BP1 d8 |BP| + (IK, DH SI


(d i re< t address)

111 |B\| [BX] i (!;% ! |BX| i (IK. BH Dl

Ml Ml IRY MODI: REGISTER MODE

d8 = O-lnt displacement dl 6 16-bit displacement


FIGURE 3-8 MOD and R/M bit patterns for 0006 instructions. The effective
address (EA) produced by these addressing modes will be added to the data-
segment base to form the physical address except for those cases where BP is
used as part of the EA. In that case the EA will be added to the stack-segment
base to form the physical address. You can use a segment-override prefix to
indicate that you want the EA to be added to some other segment base.

a 1. and put 100 in the REG field to represent SP. The the table. Read the required MOD-bit pattern from the
MOD field will be 11 to represent register addressing top of the column. In this case. MOD is 00. Then read
mode. Make the R/M field 01 1 to represent the other reg- the required R/M-bit pattern at the left of the box. For
ister, BX.
The resultant code for the instruction MOV this instruction you should find R/M to be 111. Assem-
SP,BX will be 10001011 11100011. Figure 3-9a shows blingofallthese bits together should give you 10001010
the meaning of all of these bits. 00001 1 1 1 as the binary code for the instruction MOV
If you change the D bit to a 0 and swap the codes in CL, [BX], Figure 3-9c summarizes the meaning of all the
the REG and R/M fields, you will get 10001001 bits in this result.
11011 100. which is another equally valid code for the
instruction. Figure 3-9b shows the meaning of the bits MOV 43H[SI], DH
in this form. This second form, incidentally, is the form
This instruction will copy a byte from the DH register to
that the Intel 8086 Macroassembler produces.
a memory location. The effective address of the memory
location will be computed by adding the indicated dis-
CODING MOV CL, [BX]
placement
43H toof the contents of the SI register. The
This instruction will copy a byte to CL from the memory actual physical address will be produced by shifting the
location whose effective address is contained in BX. The contents of the data segment base in DS 4 bits left and
effective address will be added to the data segment base adding this effective address to the result.
in DS to produce the physical address. The 6-bit opcode for this instruction is again 100010.
To find the 6-bit opcode for byte one of the instruc- Make the D bit a 0 because you are moving/rom a regis-
tion, consult the table in Appendix A. You should find ter. Makethe W bit a 0 because you are moving a byte.
that this code is 100010. Make the D bit a 1 because Put 110 in the REG field to represent the DH register.
data is being moved to register CL. Make the W bit a 0 The R/M field will be 100 because SI contains part of the
because the instruction is moving a byte into CL. Next effective address. Make the MOD field 01 because the
you need to put the 3-bit code which represents register displacement contained in the instruction. 43H, will fit
CL in the REG field of the second byte of the instruction in one bvte. If the specified displacement had been a
code. The codes for each register are shown in Figure number larger than FFH, then MOD would have been
3-7. In this figure you should find that the code for CL is 10. Putting all these pieces together gives 10001000
001. Now, all you need to determine is the bit patterns 01 1 10100 for the first two bytes of the instruction code.
for the MOD and R/M fields. Again use the table in Fig- The specified displacement, 43H or 0100001 1 binary is
ure 3-8to do this. To use the table, first find the box put after these two as a third instruction byte. Figure
containing the desired addressing mode. The box con- 3-9d shows this. If an instruction specifies a 16-bit dis-
taining |BX].
for example, is in the lower left corner of placement,
the then
low byte of the displacement is put

808b FAMILY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION 57


100010111 100011 MOV SP. BX 10001001 l|l|o|l|l|l|o|o| MOV
SP.BX

OPCODE FOR MOV R/M = BX OPCODE (MOV) '

'TO' REG -
L EG SP 'FROM' REG - REG BX

MOV WORD- REGISTER TO REGISTER MOV WORD- REGISTER TO REGISTER

BYTE 1 BYTE 2 1
|,|o 0 | 0 | 1| 0 ii 0 0 | 1 '!'!"! 1" 1
MOV CL, (BX] CODE
OPCOC R/M = [SI]
1 000101 000001 1 1
ROM' REG — I ;
'FROM' REG = DH
I IP I HI)!
VIOV RYTF
MOV BYTE 1 MEMORY, ONE BYTE
DISPLACEMENT
'TO' REG
1 BYTE 3
MOV BYTE MEMORY,
NO DISPLACEMENT n^ |o|o|o|o|i|i|

DISPLACEMENT = 43H

BYTE I BYTE 2
SEGMENT OVERRIDE PREFIX

H" li il 1 0| 1 1 0 0 0 | 0 | 1| 1| %
l"l I BYTE 1 I

001011
OPCODE
DIRECT
'TO' REG ' ADDRESSING
MOV WORD

BYTE 3
10001000000101 MOV CS [BX], DL
0 j 1| I | I | 1 | 0 | 1| II| 0 | I | " I '"'I n | II| I | I | MOV
CX,[437AH]
OP CODE
'
DIRECT ADDRESS DIRECT ADDRESS
'FROM' REG REG = DL
LOW BYTE HIGH BYTE
7AH 43H MOV BYTE MEMORY, NO DISPLACEMENT

(el

FIGURE 3-9 MOV instruction coding examples, la) MOV SP, BX. lb) MOV SP,
BX alternative. Id MOV CL, [BX]. Id) MOV 4?H [SI], DH. (e) MOV CX,
[437AH], If) MOV CS:[BX], DL.

in as byte three of the instruction code, and the high which is the mode specified by this instruction. For di-
byte of the displacement is put in as byte four of the rect addressing you should find MOD to be 00 and R/M
instruction code. to be 110. The first two code bytes for the instruction
then are 1000101 1 00001 1 10. These two bytes will be
CODING MOV CX, [437AH] followed by the low byte of the direct address, 7AH
(01 1 1 1010 binary) The high byte of the direct address
Tins instruction copies the contents of two memory lo-
43H (01000011 binary) will be put after that. The in-
cationsCX.
into The direct address or displacement of
struction
be willcoded into four successive memory
the first memory location from the start of the data seg-
addresses as 8BH, OEH. 7AH, and 43H. Figure 3-9e
ment
437AH.
is The physical memory address will be
spells this out in detail.
produced by shifting the contents of the data segment
register, DS, 4 bit positions left and adding this direct
CODING MOV CS:[BX], DL
address to the result.
The 6-bit opcode for this instruction is again lOOOlO. This instruction copies a byte from the DL register to a
Make the D bit a 1 and the W bit a 1 because you are memory location. The effective address for the memory
moving a word to CX. Put OOl in the REG field to repre- location is contained in the BX register. Normally an ef-
sent the
CX register, and then consult Figure 3-8 to find fective address
in BX will be added to the data segment
the MOD and R/M codes. In the first column of the fig- base in DS to produce the physical memory address. In
ure youshould find a b<>\ labeled "direct addressing." this instruction, CS: indicates that we want the BIU to

58 CHAPTER THREE
.idd the effective address to the code segmenl basi In < S \ni ) \i , on i
in produce the physical address ("he CS Is called a seg This instruction adds the immediate number 07H to the
ment ovei ride pn /i * AI. register and puts the resull in the Al. registi
When .in Instruction containing a segmenl override
simplest template to use foi coding this instruction is
prefix Is coded, an 8 bil code foi the segmenl override
found in the table in Appendix A undei the heading
prefix Is put in memorj before the code for the resl ol the
ADD Immediate to accumulator." the format is
Instruction. The code byte foi the segmenl ovei ride pre
10W, data byte, data byte. Since we are adding a
fix has the formal 001XX1 10. You Inserl a 2 bil code in
byte, the W hit should he a (I. the immediate data byte
pl.uc ol the X"s to Indicate which segment base you wanl
wi are adding will be put in the second code byte The
the effective address to be added to. I lie i tides for these
third code byte will not be needed because we are only
2 bus are .is follows 00 ES. 01 CS, 10 SS, and
adding a byte, the code then will be 00000100
I l DS. The segmenl override prefix byte foi CS then
00000111.
is 00101 l 10. For practice, code out the resl ol ihis in-
struction. Figure
3 9/ shows the result you should get
and how the code for the segment override prefix is put MOV [00001, AL
before the other code bytes for the Instruction.
This instruction copies the contents of the AL register to
a memory location. The direct address or displacement
ol the memory location fr the start of the data seg
ment is 0000H. The code template for this instruction is
Coding the Example Program
found in the table in Appendix A under the heading
Again, as you read through tins section follow the bit- "MOV — Accumulatoi to memory." The format ior the
by-bit development of the instruction codes on a sepa- instruction is 1010001W, address low byte, address
rate paper
for practice high bvte. Since the instruction moves a byte, the W bit
should be a 0. The low byte of the direct address is writ
MOV AX, 00 I OH ten in as the second instruction code byte, and the high
byte of the direct address is written in as the third in-
This instruction will move the immediate word 0010H
structionbyte.
code The codes for these 3 bytes then will
into the AX accumulator. The simplest code template to
be 10100010 00000000 00000000.
use for this instruction is listed in the table in Appendix
A under the MOV "immediate to register" heading. The
format for it is 1011 VV REG. data byte low. data byte INT 3
high. Make the W bit a 1 because you want to move a
word. Consult Figure 3-7 to find the code for the AX reg-
In most 8086 systems this instruction causes the 8086
to stop executing instructions and do nothing but wait
ister. You
should find this to be 000. Put this 3-bit code
for the user to tell it what to do next. According to the
in the REG field of the instruction code. The completed
format table in the appendix, the code for this instruc-
instruction code byte is 101 1 1000. Put the low byte of
the immediate number, 10H. in as the second code byte.
tionthe
is single byte 1 1001 100 or CCH.
Then put the high byte of the immediate data. 00H. in
as the third code byte. SUMMARY OF HAND CODING THE EXAMPLE
PROGRAM

MOV DS, AX Figure 3-4 shows the example program with all the in-
struction codes
in sequential order as you would write
This instruction copies the contents of the AX register
them so that you could load the program into memory
into the data segment register. The template to use for
and run it. Codes are in HEX to save space.
coding this instruction is found in the table in Appendix
A under the heading "Register/memory to segment reg-
ister." format
The for this template is 10001 1 10 MOD 0
segreg R/M . Segreg represents the 2-bit code for the de- A Look at Another Coding Template Format
sired segmentregister. These codes are also found in As we mentioned previously. Intel literature shows the
the table at the end of Appendix A. The segreg code for 8086 instruction coding templates in two different
the DS register is 1 1 . Since the other operand is a regis- forms. The preceeding sections have shown you how to
ter. MODshould be 11. Put the 3-bit code for the AX use the templates found in the 8086 data sheet in Ap-
register. 000, in the R/M field. The resultant codes for pendix
NowA. let's take a brief look at the second form
the two code bytes should then be 10001 110 1 101 1000. shown along with the instruction clock cycles in Appen-
dix B.
The only difference between the second form for the
IN AL, 05H templates and the form we discussed previously is that
This instruction copies a byte of data from port 05H to the D and W bits are not individually identified. Instead,
the AL register. The coding for this instruction was de- the complete opcode bytes are shown for each version of
scribed
a previous
in section. The code for the instruc- an instruction. For example, in Appendix B the opcode
tion11100100
Is 00000101. byte for the MOV memory, register 8 instruction is

8086 FAMILY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION 59


shown as 88H. and the opcode byte for the WOY mem- some features may be slightly different so consult the
ory, registerlb instruction is shown as 89H. The only manual for it.
difference between the two codes is that the W bit is a 0
for the 8-bit move and the VV bit is a 1 tor the 16-bit
move. One important point to make about using the Program Format
templates in Appendix B is that for operations which The best way to approach this section seems to be to
involve two registers, the 3-bit code for the source regis- show you a simple, but complete, program written for
ter is
put in the REG field of the MOD RM instruction an assembler and explain the function of the various
byte. The 3-bit code for the destination register is put in parts. By now you are probably tired of the "read tem-
the R M field of the MOD RM instruction byte. The in- perature,
-7. add
and store result in memory" program,
struction BX,
MOVCX, for example, is coded out as so we will use another example.
10001001 1 100101 1. or 89H CBH. You can use which- Figure 3-10 shows an 8086 assembly language pro-
ever set
of templates you find easier to use. gram whichmultiplies two 16-bit binary numbers to
give a 32-bit binary result. If you have a development
system or a computer with an 8086 assembler to work
A Few Words About Hand Coding
on. this is a good program for you to key in. assemble,
If you have to hand-code 8086 assembly language pro- and run to become familiar with the operation of your
grams,are
herea few tips to make your life easier. First, system. If you are working on a prototvping board such
check your algorithm very carefully to make sure thai it as the SDK-86. you can construct the binary codes for
really does what it is supposed to do. Second, initially each of the instructions, load the program into the on-
write down just the assembly language statements and board RAM.
and run it. In any case, you can use the
comments for your program. You can check the table in structure of this example program as a model for your
the appendix to determine how many bytes each in- own programs.
structionsotakes
you know how many blank lines to In addition to program instructions, the example pro-
leave between instruction statements. You may find it gramFigure
in 3-10 contains directions to the assem-
helpful to insert three or four NOP instructions after bler. These directions to the assembler are commonly
even' nine or ten instructions. The NOP instruction called assembler directives or pseudo operations. A sec-
doesn't do anything but kill time. However, if you acci- tion the
at end of Chapter 6 lists and describes for your

dentallyoutleavean instruction in your program, you reference a large number of the available assembler di-
can replace the NOPs with the needed instruction. This rectives. we
Herewill discuss the basic assembler direc-
way you don't have to rewrite the entire program after tives you
need to get started writing programs. We will
the missing instruction. introduce more of these directives as we need them in
After you have written down the instruction state- the next two chapters.
ments, recheck
very carefully to make sure you have the
right instructions to implement your algorithm. Then,
work out the binary codes for each instruction and write SEGMENT and ENDS Directives
them in the appropriate places on the coding form.
The SEGMENT and ENDS directives are used to identify
Hand coding is laborious for long programs. When
a group of data items or a group of instructions that you
writing long programs, it is much more efficient to use
want to be put together in a particular segment. These
an assembler. The next section of this chapter shows
directives are used in the same way that parentheses are
you how to write your programs so you can use an as-
used to group like terms in algebra. A group of data
sembler
produce
to the machine codes for the instruc-
tions. statements or a group of instruction statements con-
tained between
SEGMENT and ENDS directives is called
a logical segment. When you set up a logical segment.
you give it a name of your choosing. In the example
WRITING PROGRAMS FOR USE WITH program the statements DATA HERE SEGMENT and
AN ASSEMBLER DATA HERE ENDS set up a logical segment named
DATA HERE. There is nothing sacred about the name
If you have an 8086 assembler available, you should DATA HERE. We simply chose this name to help us re-
learn to use it as soon as possible. Besides doing the memberthis
that logical segment contains data state-
tedious task of producing the binary codes for vour in- ments. The
statements CODE HERE SEGMENT and
struction statements,an assembler also allows you to CODE HERE ENDS in the example program set up a logi-
refer to data items by name rather than by numerical cal segment named CODE HERE which contains in-
addresses. As you should soon see. this greatlv reduces struction statements.
The Intel and the IBM 8086 macro
the work you have to do and makes your programs assemblers, incidentally, allow you to use names and
much more readable. In this section we show you how to labels of up to 31 characters. You can't use spaces in a
write your programs so that you can use an assembler name, but you can use an underscore as shown to sepa-
on them. The assemblers used for the programs in this rate wordsin a name. Also, you can't use instruction
book were the Intel 8086 8088 80186 80188 M mnemonics as segment names or labels. Throughout
sembler and the Microsoft Macro Assembler for the IBM the rest of the program you will refer to a logical segment
Personal Computer. If you are using another assembler. bv the name that vou give it when vou define it.

60 CHAPTER THRFE
PAGI ,132 M ,i e listing file line! ' : ers w i do
18036 pi %¡g i .mi
; ABSTRACT I Ii I • I 'I i ii M 'Hi ffll I I. t 1 I %] 1 i " till' I W( ' 16 I'll t'i it il I
the memi <\ . Location: called Ml II (ill l CAI ID
MU1 TIPLIER. I In • resul 1 i • stored Ln thi n
i di at ion cal led PRODUCT
;P0R1 B USED : None
;PROCI DI IRI S IS! D: None
;ri listers u 3ED : CS , Di ;., DX and AX

DATA_HERE SEGMf N 1

MULT I PL ICAND DW 204AH fin I w< hi! here


MULTIPLIER DW 'H.Mll second wor d here
PRODUCT DW 2 DUP(0) i i •% iilt here

DATA HERE ENDS

CODE HERE SEGMENT


ASSUME CS CODE HERE DS : DATA._HERE

MOV AX, DATA HERE ; i n i t i a 1 i z e DS r eg i st er


MOV DS,AX

MOV AX, MULTIPLICAND get one word


MUL MULT IPLIER multiply by second word
MOV PRODUCT, AX store low word of result
MOV PRODUCT h-2, DX store high word of result
INT 3 wa i t -for com rn a n d f r o m u s e r

CODE HERE ENDS


END

FIGURE 3-10 Assembly language source program to multiply two 16-bit binary
numbers to give a 32-bit result.

A logical segment is not usually given a physical start- them by name rather than having to remember or calcu-
ing address when it is declared. After the program is late their value each time you refer to them in an in-
assembled, and perhaps linked with other assembled struction.
otherIn words, if you give names to con-
program modules, it is then assigned the physical ad- stants, variables, and addresses the assembler can use
dress where
it will be loaded in memory to be run. these names to find the desired data item or address
when you refer to it in an instruction. Specific directives
are used to give names to constants and variables in
Data and Addresses Naming Directives — EQU, your programs. Labels are used to give names to ad-
DB, DW, and DD dresses
yourin programs.

Programs work with three general categories of data:


constants, variables, and addresses. The value of a con-
THE EQU DIRECTIVE
stant does
not change during the execution of the pro- The EQU or equate directive is used to assign a name
gram. The
number 7 is an example of a constant you to constants used in your programs. The statement
might use in a program. A variable is the name given to CORRECTION FACTOR EQU 07H, in a program such as
a data item which can change during the execution of a our previous example, would tell the assembler to insert
program. The current temperature of an oven is an ex- the value 07H every time that it finds the name
ample
a variable.
of Addresses are referred to in many CORRECTION FACTOR in a program statement. In
instructions. You may. for example, load an address other words, when the assembler reads the statement
into a register or jump to an address. ADD AL, CORRECTION FACTOR, it will automatically
Constants, variables, and addresses used in your pro- code the instruction as if you had written it ADD AL,
grams can
be given names. This allows you to refer to 07H. Here's the advantage of using an EQU directive to

808b FAMItY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION 61


declare constants at the start of your program. Suppose MEMOF %

that you use the correction factor of -07H 23 times in


vour program. Now the company you work for changes
"iperature sensor and the new correction
factor is -09H. If you used the number 07H in the 23
:ons which contain this correction factor, then
HIGH WORD -
e to go through the entire program, find each
instruction that uses the correction factor, and update
_OWV = •
the value. Murphy's law being what it is. you are likely to
miss one or two of these, and the program won't work
correcdy. If you used an EQU at the start of your pro- . wu LT pL E.
gram and
then referred to CORRECTION TACTOR by
name in the 23 instructions, then all you do is change
START DF ML LT -- =AND
the value in the EQU statement from 07H to 09H and : -~- -e 2 e

reassemble the program. The assembler automatically


inserts the new value of 09H in all 23 instructions.
FIGURE 3-11 Data arrangement in memorv for multiplv
NOTE In large programs consisting of modules assem-
program.
bled separately, constants must be declared in each mod-
ule. The
assembler has no way to remember an EQU value
the name MULTIPLIER. When the program is loaded,
from one module when it assembles another module.
the first memory address will be initialized with 2AH.
and the second memory location with 3BH.
DB. DW. A\D DD DIRECTIVES
The third data declaration example in Figure 3-10.
The DB. DW. and DD directives are used to assign PRODUCT DW 2 DLPO . sets aside storage for two words
names to variables in your programs. The DB directive in memory and gives the starting address of the first
after a name specifies that the data is of type byte. The word the name PRODUCT. The DUPlO) part of the state-
program statement 0\ EN TEMPERATURE DB 2". for ex- ment tells
the assembler to initialize the two words to all
ample declaresa variable of type byte and gives it the zeros. When we multiply two 16-bit binary numbers, the
name OVEN". TEMPERATURE. D\V is used to specify product can be as large as 32 bits. Therefore, we must
that the data is of type trord (16 bits I. and DD is used to set aside this much space to store the product. We could
specify that the data is of type double word 132 bits). If have used the DD directive to declare PRODUCT as a
a number is written after the DB. D\V. or DD. the data double word. but. since in the program we move the re-
item will be initialized with that value when the pro- sult PRODUCT
to one word at a time, it is more conven-
gramloaded
is from disk into RAM. The statement ient to
declare PRODUCT as 2 words.
COW ERSIOV FACTORS DB 2~H.48H.32H.69H will de- Figure 3-1 1 shows how the data for MULTIPLICAND.
clare
data
a item of 4 bytes and initialize the 4 bytes with MULTIPLIER, and PRODUCT will actually be arranged
the specified 4 values. If we don't care what a data item in memory starting from the base of the DATAJTERE
is initialized to then we can indicate this with a segment. The first byte of MULTIPLICAND. 4AH. will be
in the statement TARE_\VEIGHT D\Y ?. Note that data at a displacement of zero from the segment base, be-
variables which are changed during the operation of a cause MULTIPLICAND is the first data item declared in
program should also be initialized with program in- the logical segment DATA_HERE. The displacement of
structions
that so the program can be rerun from the the second byte of MULTIPLICAND is 0001. The dis-
start without reloading it to initialize the variables. Fig- placement
the firstof byte of MULTIPLIER from the seg-
ure 3-10shows three more examples of naming and ini- ment base
is 0002H. and the displacement of the second
tializingitems.
data byte of MULTIPLIER is 0003H. These are the displace-
The first example. MULTIPLICAND DW 204AH. de- ments that
we would have to figure out for each data
clares
dataa word named MULTIPLICAND, and initial- item if we were not using names to refer to them.
izes thatdata word with the value 204AH. What this If the logical segment DATA_HERE is eventually put in
means is that the assembler will set aside two successive ROM or EPROM. then MULTIPLICAND will function as a
memory locations and assign the name MULTIPLICAND constant, because it cannot be changed during program
to the first location. As you will see. this allows us to execution. However, if DAT.A^HERE is eventually put in
access the data in these memory locations bv name. The RAM then MULTIPLICAND can function as a variable
MULTIPLICAND DW 204AH statement also indicates that because a new value could be written in those memory
when the final program is loaded into memory to be run. locations during program execution.
these memory locations will be loaded with I initialized
to) 204AH. Actually, since this is an Intel microproces-
sor, thefirst address in memory will contain the low T\pes of Numbers Used in Data Statements
byte of the word. 4AH. and the second memory address All of the previous examples of DB. DW. and DD declara-
will contain the high byte of the word. 20H. tions use
hexadecimal numbers as indicated by an "H"
The second data declaration example in Figure 3-10. after the number. You can. however, put in a number in
MULTIPLIER DW 3B2AH. sets aside storage for a word in any one of several other forms. For each form you must
memory and gives the starting address of this word tell the assembler which form vou are using.

hi CHAPTER THREE
bin \ka structions
the m CODE HERE section ol the 11
111 Figure 3 10, find the instruction MOV \\
Foi example, when you use a binary numbei In .1 state
VII I riPLK AND llns ins tion, when executed, will
ment, you put a B aftei the string oi 1'sandO's to let the
copy a word hum memory to the AX registei When the
assemble) know that you want the number to be treated
assemblei reads through this program the lust time, it
as a binary number. The statemenl 11 Ml' MAX DB
will automatically calculate the displacement ol -
01 1 1 1001 B is an example. II you want to put In a negative
the named data items from the segment base
binary number, write the number in its 2 s complement
DATA HERE. Referring to Figure 3 I I you can sec thai
si^ii and-magnitude form.
the displacemenl ol MULTIPLICAND from the segment
( X IAI base Is 0000. This is because MULTIPLICAND is the firsl
data Hem dec Tared in the segment. The assembler, then,
To Indicate that you want a number to be evaluated as
will find that the displacement ol MULTIPLICAND is
base 8 or octal, put a Q after the string oi octal dibits.
00001 1. When the assembler reads the program the sec
rhe statemenl OLD COMPUTER DW 7341 Q is an example.
ond lime to produce the binary codes tor the instruc
lions. 11 will insert Ibis displacement as part ol the bi
DECIMAL
nary code tor the instruction MOV AX, MUI Ill'l K AND.
ITie assemble! Heats a 111mil mi with no identifying lei Since we know that the displacement of MULTIPLK AM )
tei after it as a decimal number. In other words, if you is 0000. we could have written the instruction as MOV
forget to put an H alter a number that you want the AX, |0000|. However, there would be a problem if we latei
assembler to treat as hexadecimal, the assembler will changed the program by adding another data item be-
treat it as a decimal number. The assembler automati- fore MULTIPLICAND in DATA HERE. The displacemenl
cally converts a decimal number in a statement to bi- of MULTIPLICAND would be changed. Therefore, we
nary the
so value can be loaded into memory. The state- would have to remember to go through the entire pro-
ment TEMPERATURE MAX DB 49 is an example. If you gram and
correct the displacement in all instructions
indicate a negative number in a data declaration state- that access MULTIPLICAND. If you use a name to refer to
ment, the
assembler will convert the number to its 2's each data item as shown, the assembler will automati-
complement sign-and-magnitude form. For example, cally calculate the correct displacement of that data item
given the statement TEMP MIN DB -20. the assembler for you and insert this displacement each time you refer
will insert the value 11101 100. which is the 2's comple- to it in an instruction.
ment representation for -20 decimal. To summarize how this works, then, the instruction
NOTE You can put a D after decimal values if you want MOV AX, MULTIPLICAND is an example of direct ad-
to more clearly indicate that the value is decimal. dressing where
the direct address or displacement
within a segment is represented by a name. For instruc-
HEXADECIMAL tions such
as this, the assembler will automatically cal-
culatedisplacement
the of the named data item from the
As shown in several previous examples, a hexadecimal
start of the segment and insert this value as part of the
number is indicated by an H after the hexadecimal dig-
binary code for the instruction. When the instruction
its. The
statement MULTIPLIER DW 3B2AH is an example.
executes, the BIU will add the displacement contained
in the instruction to the data segment base in DS. (Re-
ASCII
member,
contents
the of DS are shifted 4 bit positions
ASCII characters can be put in data declaration state- left before the displacement is added.) This addition
mentsenclosing
by them in single quotation marks. produces the 20-bit physical address needed to address
The statement BOY 1 DB 'ALBERT, for example, tells the the data named MULTIPLICAND in memory.
assembler to set aside six memory locations named The next instruction in the program in Figure 3-10 is
BOY 1 . It also tells the assembler to put the ASCII code another example of direct addressing using a named
for A in the first memory location, the ASCII code for L in data item. The instruction MUL MULTIPLIER multiplies
the second, the ASCII code for B in the third, etc. The the word named MULTIPLIER in DATAJTERE times the
assembler will automatically determine the ASCII codes word in the AX register. The low word of the result is left
for the letters or numbers within the quotes. in the AX register, and the high word of the result is left

NOTE ASCII can only be used with the DB directive. in the DX register. When the assembler reads through
this program the first time, it will find the displacement
DECIMAL REAL AND HEXADECIMAL REAL of MULTIPLIER in DATA HERE is 0002H. When it reads
through the program the second time it inserts this dis-
These two types are used to represent noninteger num-
placement
part as of the binary code for the MUL in-
bers suchas 3.14159. We will discuss how these are
struction. When
the MUL MULTIPLIER instruction exe-
used in Chapter 11.
cutes, the
BIU will add the displacement contained in
the instruction to the data segment base in DS to ad-
Accessing Named Data with Program dress MULTIPLIER in memory.
Instructions The next instruction, MOV PRODUCT, AX. in the pro-
Now that we have shown you how the data structure is gramFigure
in 3-10 copies the low word of the result
set up, let's look at how program instructions access from AX to memory. The low bvte of AX will be copied to
this data. Temporarily skipping over the first two in- a memory location named PRODUCT. The high byte of

8(l8h FAMIIY ASSEMBLY LANGUAGE PROGRAMMING — INTRODUCTION 63


AX will be copied to the next higher address which we CS:CODE_HERE, DS:DATA_HERE tells the assembler that
can refer to as PRODUCT + 1. the logical segment CODE HERE contains the instruc-
The following instruction in the program, MOV tion statements for the program and should be treated
PRODUCT + 1, DX. copies the high word of the multipli- as a code segment. It also tells the assembler that it
cation result
from DX to memory. When the assembler should treat the logical segment DATA HERE as the
reads this instruction, it will add the indicated "2" to data segment for this program. In other words, the
the displacement it calculated for PRODUCT and insert DS:DATA HERE part of the statement tells the assembler
the result as part of the binary code for the instruction. that, for any instruction which refers to data in the data
Therefore, when the instruction executes, the low byte segment, that data will be found in the logical segment
of DX will be copied to memory at a displacement of DATA HERE. The ASSUME . . . DS:DATA HERE, for ex-
PRODUCT + 2. The high byte of DX will be copied to a ample, tells
the assembler that a named data item such
memory location which we can refer to as PRODUCT + as MULTIPLICAND is contained in the logical segment
3. Figure 3-1 1 shows how the two words of the product called DATA HERE. Given this information, the assem-
are put in memory. Note that the lower byte of a word is bler canconstruct the binary codes for the instruction.
always put in the lower memory address. The displacement of MULTIPLICAND from the start of
This example program should show you that if you are DATA HERE will be inserted as part of the instruction
using an assembler, names are a very convenient way of by the assembler.
specifying the direct address of data in memory. If you are using an assembler, you must use an
ASSUME statement in your program. Also, if you are
Naming Addresses — Labels using the stack segment and the extra segment in your
Names representing addresses are called labels. They program, you must include terms in the statement to
are written in the label field of an instruction statement tell the assembler the name of the logical segment to use
or a directive statement. One major use of labels is to for the stack and the name of the logical segment to use
represent the destination for jump and call instruc- for the extra segment. These additional terms might
tions. Suppose,
for example, we want the 8086 to jump look like: SS:STACK HERE, ES:EXTRA__HERE. As we will
back to some previous instruction over and over. In- show later, you can put another ASSUME directive later
stead
computing
of the numerical address that we want in the program to tell the assembler to use different logi-
to jump to. we put a label in front of the instruction we cal segments from that point on.
If the ASSUME directive is not completely clear to you
want to jump to and write the jump instruction as )MP
at this point, don't worry. We show many more examples
label. Here is a specific example.
of its use thoroughout the rest of the book. We intro-
NEXT: IN AL. 05H ; Get data sample form port 05H duced ASSUME
the directive here because you need to
put it in your programs for most 8086 assemblers. You
: Process data value read in.
can use the assume statement in Figure 3-10 as a model
of how to write this directive for your programs.

J MP NEXT ; Get next data value and process

Initializing Segment Registers


If you use a label to represent an address as shown in
The ASSUME directive tells the assembler the names of
this example, the assembler will automatically calculate
the logical segments to use as code segment, data seg-
the address that needs to be put in the code for the jump
ment, stack
segment, and extra segment. The assembler
instruction. The next two chapters show many exam-
uses displacements from the start of the specified logical
plesthe
of use of labels with jump and call instructions.
segment to code out instructions. When the instruc-
Another example of using a name to represent an ad-
tions are
executed, the displacements in the instruc-
dress
in isthe SEGMENT directive statement. The name
tions will
be added to segment registers to produce the
DATA HERE in the statement DATA HERE SEGMENT, for
actual physical addresses. The assembler, however, can-
example, represents the starting address of a segment
not directlyload the segment registers with the starting
named DATA HERE. Later we show you how we use this
physical addresses of the segments.
name to initialize the data segment register. We will now
The segment registers, other than the code segment
discuss some other parts of the example program that
register, must be initialized by program instructions
you will need to use in your programs.
before they are used to access data. The first two in-
structions
the example
of program in Figure 3-10 show
The ASSUME Directive
how this is done for the data segment register.
An 8086 program may have several logical segments DATA_HERE in the first instruction represents the
which contain code, several that contain data, and sev- upper 16 bits of the starting address you give the seg-
eral that
can serve as a stack. However, at any given time ment DATA HERE. Since the 8086 does not allow us to
the 8086 works directly with only four physical seg- move this immediate number directly into the data seg-
ments:
codea segment, a data segment, a stack .seg- ment register,
we must first load it into one of the gen-
ment, and
an extra segment. The ASSUME directive eral-purpose andregisters
then copy it into the data seg-
tells the assembler which logical segment to use for each ment register.MOV AX, DATATHERE loads the upper 16
of these physical segments at a given time. bits of the segment starting address into the AX regis-
In Figure 3-10, for example, the statement ASSUME ter. MOV DS, AX copies this value from AX to the data

64 ("HAI'UR IHKtl
segment reglstei rhis is the same operation we de
scribed for hand coding the example program In Figure
3 \. except that here we use the segment name instead
ol .1 number to refei to the segment base addi ess In this
example we used the AX registei to pass the value, but
an) 16 bit register othei than a segment register can be
used it you in hand coding youi programs, yi
just insert the uppei 16 bits ol the 20 bit segment stai t
Ing address in place ol DATA 1IERE in the instru< tion
For example, u in your pai t icular system you decide to
locate DATA HERE at address 00300H, DS should be
loaded with 0030H It you are using an assemble] . you
can use the segment name to refer to its base address as
shown in the example.
If you use the stack segment and the extra segment in
.i program, the stack segmenl register and the extra seg
ment register must also be initialized by program in-
structions
the same in way
\V1ifii the assembler reads through your assembly Ian
guage program, it calculates the displacement ol each
named variable from the start ol the logical segment
that contains it. The assembler also keeps track ol the FIGURE Mi Applied Microsystems is 1800 16-bit
displacement of each instruction code byte from the emulator. (Applied Microsystems ( orp.)
start of a logical segment. The CS:CODE HERE part of
the ASSUMED statement in Figure 3-10 tells the assem- ment tools to make your work easier These systems
blercalculate
to the displacements of the following in- usually contain several hundred Kbytes of RAM. a key-
structionsthe from start of the logical segment board video
and display, floppy and or hard disk drives,
CODE HERE. In other words, it tells the assembler a printer, and an emulator. Figure 3 12 shows an Ap-
that, when this program is run. the code segment regis- plied MicrosystemsES 1800 16-bit emulator which can
ter willcontain the upper 16-bits of the address where be added to an IBM PC/AT or compatible computer to
the logical segment CODE HERE was located in mem- produce a complete 8086/80186/80286 development
ory. Theinstruction byte displacements that the assem- system. The following sections give you an introduction
blerkeeping
is track of are the values that the 8086 will to several common program development tools which
put in the instruction pointer, IP. to fetch each instruc- you use with these systems. Most of these tools are pro-
tion byte. grams which
you run to perform some function on the
There are several ways that the CS register can be program you are writing. You will have to consult the
loaded with the code segment base address and the in- manuals foi your system to get the specific details for it.
struction pointer
can be loaded with the displacement of but this section should give you an overview of the steps
the instruction byte to be fetched next. The first way is involved in developing an assembly language microcom-
with the command you give your system to execute a puter programusing a system. An accompanying lab
program starting at a given address. A typical command manual steps you through the use of all these tools with
ol this sort is G = 0010:0000 <CR > . (<CR > means the SDK-86 board and the IBM Personal Computer.
"press the return key.") This command will load CS with
0010 and load IP with 0000. The 8086 will then fetch
Editor
and execute instructions starting from address 00100, An editor is a program which, when run on a system,
the address produced when the BIU shifts CS and adds lets you type in the assembly language statements for
IP. The other ways of loading CS and IP will be discussed your program. Examples of editors are ALTER which
in later sections. runs on Intel systems. EDLIN which runs on IBM PCs.
and Wordstar which runs on most systems. The main
The END Directive function of an editor is to help you construct your as-
sembly language
program in just the right format so
The END directive, as the name implies, tells the assem-
that the assembler will translate it correctly to machine
bler stop
to reading. Any instructions or statements
language. Figure 3-10 shows an example of the format
that you write after an END directive will be ignored
you should use when typing in your program. This form
of your program is called t he source program. The actual
ASSEMBLY LANGUAGE PROGRAM position of each field on a line is not important, but you
DEVELOPMENT TOOLS must put the fields of each statement in the correct
order, and you must leave at least one blank between
Introduction fields. Whenever possible, we like to line the fields up in
For all but the very simplest assembly language pro- columns so that it is easier to read the program.
gramswill
youprobably want to use some type of micro- As you type in your program, the editor stores the
computer development
system and program develop ASCII codes for the letters and numbers in successive

»()8b FAMILY ASSEMBLY LANGUAGE PR< x .KAMMING — INTRODUCTION 65


RAM locations. If you make a typing error the editor will The trailer section of the listing in Figure 3-13 gives
let you back up and correct it. If you leave out a program some additional information about the segments and
statement, the editor will let you move everything down names used in the program. The statement CODE HERE
and insert the line. This is much easier than working 0014 PARA NONE, for example, tells you that the segment
with pencil and paper, even if you type as slowly as I do. CODE_HERE is 14H bytes long and will be located at a
When you have typed in all of your program, you then physical address whose lower 4 bits are 0000. The state-
copy it from memory to a file on a floppy or hard mag- ment MULTIPLIER. . . . L WORD 0002 DATA HERE tells
netic disk.
This file, such as the one in Figure 3-10. is you that MULTIPLIER is a variable of type word and that
called a source file. If you later find that your program it is located at an offset of 0002 in the segment
contains errors, you can use the editor to load the DATA HERE.
source file back into RAM and make the needed correc-
tionsthe
in source program. Linker
A linker is a program used to join together several object
Assembler files into one large object file. When writing large pro-
An assembler program is used to translate assembly grams
is usually
it much more efficient to divide the
language mnemonics to the correct binary code for each large program into smaller modules. Each module can
instruction. The assembler will read the source file of be individually written, tested, and debugged. When all
your program from the disk where you saved it after ed- of the modules work they can be linked together to form
iting.assembler
An usually reads your source file more a large functioning program. Also, the object modules
than once. On the first pass through the source pro- for useful programs, a square root program, for exam-
gram,assembler
the finds everything. It determines the ple, can
be kept in a library file and linked into other
displacement of named data items and the offset of la- programs as needed.
bels, and
puts this information in a symbol table. On a The linker produces a link file which contains the
second pass through the source program, the assembler binary codes for all the combined modules. The linker
produces the binary code for each instruction and as- also produces a link map file which contains the ad-
signs addressesto each. dress information about the linked files. The linker,
The assembler generates two files on the floppy or however, does not assign absolute addresses to the pro-
hard disk. The first file is called the object file. The ob- gram,
only
it assigns relative addresses starting from
ject file
contains the binary codes for the instructions zero. This form of the program is said to be relocatable.
and information about the addresses of the instruc- because it can be put anywhere in memory to be run. If
tions. This
file contains the information that will even- you are going to run your program on a system such as
tuallyloaded
be into memory and executed. The second the IBM PC, you can just load the link file into memory
file generated by the assembler is called the assembler and run it. If you are going to run your program on a
list file. Figure 3-13 shows the assembler list file for the system such as the Intel Series IV. then you must use a
source program in Figure 3-10. This file contains the locator program to assign absolute addresses to the
assembly language statements, the binary codes for linker file.
each instruction, and the offset for each instruction.
You usually send this file to a printer so that you will Locator
have a printout of the entire program to work with when A locator is a program used to assign the specific ad-
you are testing and troubleshooting the program. The dresses
where
of the object code is to be loaded into
assembler listing will also indicate any typing or syntax memory. A locator program that comes with the IBM PC
(assembly language grammar) errors you made in typing Disk Operating System (DOS) is called EXE2BIN. Here's
in your source program. how you proceed if you want to produce a program with
absolute addresses that you can download to an SDK-86
NOTE The assembler will not tell you if you made a pro-
from an IBM PC. First build a source (.ASM| file using
grammingYou
error. usually have to run the program to
the EDLIN or perhaps the WORDSTAR editor. Assemble
find these. To correct the errors indicated on the listing,
the source file with the IBM PC Macroassembler (MASM)
you use the editor to reedit your source program and
to produce the .OBJ file. Use the LINK program to pro-
save the corrected source program on disk. You then
duce
relocatable
a .EXE file. Then use the EXE2BIN pro-
reassemble the corrected source program. It may take
gram
give
to your program an absolute starting address
several times through the edit-assemble loop before you
such as 0010:0000H. Finally, use the SDKDMP program
get all of the syntax errors out of your source program.
from Chapter 13 to download the .BIN file produced by
Now let's take a look at some of the information given
EXE2BIN and run it. In some systems a single program
on the assembler listing. The left-most column in the
performs both the link and the locate functions.
listing gives the offsets ol data items from the start of
the data segment and the offsets of code bytes from the
start of the code segment. Note that the assembler does Debugger
nol generate absolute physical addresses. A linker or If your program requires no external hardware or re-
lo( ator will do this later. Also note that the MOV AX, quires only
hardware accessible directly from your sys-
DATA HFRE statement is assembled with some blanks tem, then
you can use a debugger to run and debug
alter the basic instruction code because the start of DS your program. A debugger is a program which allows
is nol known at the time the program is assembled. you to load your object code program into system mem-

66 CHAPTER THREE
The IBM Personal Computer MACROAssembler 03-06-85 PA6E 1-1
PAGE ,132 ; Makes listing file lines 13? characters wide
;8086 program
".ABSTRACT : This program multiplies the two 16-bit words in
; the memory locations called MULTIPLICAND and
! MULTIPLIER. The result is stored in the memory
; location called PRODUCT
i PORTS USED : None
! PROCEDURES USED: None
REGISTERS USED : CS. DS, DX and AX

0000 DATAHERE SEGMENT

0000 2040 MULTIPLICAND DW 204AH first word here


0002 3B2A MULTIPLIER DW 3B2AH second word here
M04 02 l PRODUCT DW 2 DUP!0) result here
0000
ji

0008 DATA.HERE ENDS

0000 CODE.HERE SEGMENT


ASSUME
CS : CODE.HERE.DS : DATA.HERE

0000 B8 — - R MOVAX, DATA.HERE initialize DS register


0003 3E D8 MOVDS.AX

0005 Al 0009 R MOVAX, MULTIPLICAND get one word


0003 F7 26 0002 R MUL MULTIPLIER multiply by second word
000C A3 0004 R MOVPRODUCT, AX store low word of result
000F 89 16 0006 R MOVPRODUCT+2, DX store high word of result
0013 CC INT 3 wait for command from user

3014 CODE.HERE ENDS


END

The IBMPersonal Computer MACRO


Assembler 03-06-35 PAGE Symbols-1

Segments and groups:

Name Size al ion combine class

CODE.HERE. 0014 PARA NONE

DATAHERE. 1008 PARA NONE

Symbols:
Name Type Value Attr

MULTIPLICAND L WORD0000 DATA.HERE


MULTIPLIER . L WORD0002 DATA.HERE
PRODUCT. . . L WORD0004 DATAHERE Length =0002

Warning Severe
Errors Errors
0 0
FIGURE 3-13 Assembler listing lor example program in Figure 5-10

8086 FAMILY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION 67


ory. execute (he program, and troubleshoot or "debug"
it. The debugger allows you to look at the contents of
registers and memory locations after your program
runs. It allows you to change the contents of registers
and memory locations and rerun the program. Some
debuggers allow you stop execution after each instruc-
tionyou
so can check or alter memory and register con-
tents.
debugger
A also allows you to set a breakpoint at
any point in your program. When you run the program
the system will execute instructions up to this break-
point and stop. You can then examine register and
memory contents to see if the results are correct at that
point. If the results are correct, you can move the break-
point
a tolater point in the program. If the results are
not correct, you can check the program up to that point
to find out why they are not correct. The debugger tools
can help you isolate a problem in your program. Once
you find the problem, you can then cycle back and cor-
rect the
algorithm if necessary. You then use the editor
to correct your source program, reassemble the cor-
rected source program, relink, and run the program
again.
Microprocessor prototyping boards such as the SDK-
86 contain a debugger program in ROM. On boards
such as this the debugger is commonly called a monitor
program because it lets you monitor program activity.
The SDK-86 monitor program, for example, lets you
enter and run programs, single step through programs,
examine register and memory contents, and insert
breakpoints. The DEBUG program, used with the IBM
PC, allows you to do the same functions and also has a
trace function which shows you the contents of all the
registers after each instruction executes.

Emulator
Another way to run your program is with an emulator.
An emulator is a mixture of hardware and software. It is
usually used to test and debug the hardware and soft-
wareanof external system such as the prototype of a
microprocessor-based instrument. Part of the hardware
of an emulator is a multiwire cable which connects the
host system to the system being developed. A plug at the
end of the cable is plugged into the prototype in place of
its microprocessor. Through this connection the soft-
waretheof emulator allows you to download your object-
code program into RAM in the system being tested and
run it. As with a debugger, an emulator allows you to
load and run programs, examine and change the con-
tentsregisters,
of examine and change the contents of
memory locations, and insert breakpoints in the pro-
gram. emulator
The also takes a "snapshot" of the con-
1 registers, activity on the address and data bus.
and the state of the flags as each instruction executes. The
emulator stores this trace data, as it is called, in a large
RAM. You can do a printout of the trace data to see the re-
sults that
your program produced on a step by-step basis.
Another powerful feature of an emulator is the ability
to use either system memory or the memory on the pro-
totype lor the program you are debugging. In a later C STOP J
chapter we diseuss in detail the use ol an emulator in
developing a microprocessor-based producl FIGURE 3-14 Program development algorithm.

Mi < IIAI'ItR THKtF


Summary of the Use of Program Development flowcharts and flowcharl symbols
Tools Structured programming
Figure 3 I I shows In diagram form the order in which
1'seudocode
you will use the program development tools we have de
scribed. The first and most importanl step is to think lop down .ind hot torn up design
out very carefully what you want the program to do and
how you want the program to do it. Next, use an edltoi Sequence, repetition, and decision operations
in create the source lilt- for your program. Assemble the IF— THEN— ELSE. IF rHEN. WHILE DO,
source file with the assembler. II the assemble! lisl file REPEAT -UNTIL, and CASE structures
indicates any (inns m your program, use the editoi to
correct these errors. Cycle through the edil assemble 81 186 nisi i in t ion types

loop until the assembler uils you on the listing thai it Mnemonics
found nn errors, li your program consists oi several
modules, then use i he linker to join their object modules Initializal ion list

together Into one large object module.


standard program format
NOT! On some systems such as the IBM PC you must
Documentation
use the linker even if your program has only one mod-
ule. Instruction template: W-bit, MOD. R/M. D-bit
Now. if your system requires it. use the locate pro-
Segment-override prefix
gramspecify
to where in memory you want your pro-
grambetoput. Your program is now ready to be loaded Assembler
into memory and run. If your program does not interact
Assembler directives: SEGMENT, ENDS. END. DB.
with any external hardware other than that connected
DW. DD. EQU. ASSUME
directly to the system, then you can use the system
debugger to run and debus; your program. If your pro- Named data items
gramintended
is to work with external hardware such
as the prototype of a microprocessor-based instrument, Development tools
then you will probably use an emulator to run and Editor
debug your program. We will be discussing and showing
Linker: library file, link files, link map, relocatable
the use of these program development tools throughout
the rest of this book, but this section should give you an Locator
overview.
Debugger, monitor program
Emulator, trace data
CHECKLIST OF IMPORTANT TERMS AND
CONCEPTS IN THIS CHAPTER

If you do not remember any of the terms or concepts in


the following list, use the index to find them in the
chapter.

Algorithm

Sequential task list

REVIEW QUESTIONS AND PROBLEMS


1. List the major steps in developing an assembly lan- 5. A program is like a recipe. Use a flowchart or
guage program. pseudocode to show the algorithm for the following
recipe. The operations in it are sequence and rep-
2. What is the main advantage of a top-down design etition. Instead
of implementing the resulting
approach to solving a programming problem? algorithm in assembly language, implement it in
3. Why is it necessary to develop a detailed algorithm your microwave and use the result to help you get
lor a program before writing down any assembly through the rest of the book.
language instructions? Peanut Brittle:
4. a. What are the three basic structure types used
1 cup sugar 1 teaspoon butter
0.5 cup white corn syrup 1 teaspoon vanilla
when writing programs?
1 cup unsalted peanuts 1 teaspoon baking soda
b. What is the advantage of using only these
structures when writing the algorithm lor a i. Put sugar and syrup in 1.5 quart casserole
program? (with handle) and stir until thoroughly mixed.

8118b FAMItY ASSEMBLY LANGUAGE PROGRAMMING— INTRODUCTION i,<)


ii. Microwave at HIGH setting for 4 minutes. ES 6000 DATA SEGMENT
C5 4000 5000CH D7
iii. Add peanuts and stir until thoroughly mixed.
SS 7000 5000BH 9 A
iv. Microwave at HIGH setting for 4 minutes. Add
DS 5000 5000AH 7C
butter and vanilla, stir until well mixed and
IP 43E8 50009H DB
microwave at HIGH setting for 2 more min-
50008H C3
utes.
AH AL 50007H B2
v. Add baking soda and gently stir until light and
AX ^2 35 50006H 49
foamy. Pour mixture onto nonstick cookie
50005H 21
sheet and let cool for 1 hour. When cool, break
BH BL 50004H B9
into pieces. Makes 1 pound.
BX 07 5A 50003H 71
6. Use a flowchart or pseudocode to show the algo-
50002H 22
rithmaforprogram which gets a number from a
GH CL 50001H 4A
memory location, subtracts 20H from it, and out-
puts 01H
to port 3AH if the result of the subtrac- CX 00 04 50000H 3B

tiongreater
is than 25H.
DH DL
7. Given the register contents in Figure 3-15. answer
DX 33 02
the following questions:
a. What physical address will the next instruction
be fetched from?
b. What is the physical address for the top of the
stack?
SP 0000
8. Describe the operation and results of each of the
BP 2468
following instructions, given the register contents
SI 4C00
shown in Figure 3-15. Include in your answer the
DI 7D00
physical address or register that each instruction
will get its operands from and the physical address FIGURE 3-15 8086 register and memory contents tor
or register that each instruction will put the result. Problems 7, 8, and 10.
Use the instruction descriptions in Chapter 6 to
help you. Assume that the instructions below are
independent, not sequential unless listed together
under a letter. Write the 8086 instruction which will perform the
a. MOV AX, BX k. OR CL. BL
indicated operation. Use the instruction overview
b. MOV CL, 37H L NOT AH
in this chapter and the detailed descriptions in
c. INC BX m. ROL BX, 1
Chapter 6 to help you.
d. MOV CX, [246BH] n. AND AL. CH
MOV DS. AX
a. Copies AL to BL
e. MOV CX. 246BH a
b. Loads 43H into CL
/. ADD AL, DH P- ROR BX. CL
c. Increments the contents of CX by one
9- MUL BX <l AND AL. OFH
d. Copies SP to BP
h. DEC BP r. MOV AX, [BX]
e. Adds 07H to DL
i. DIV BL S. MOVIBX1ISI1. CL
f. Multiplies AL times BL
j- SUB AX. DX
g. Copies AX to a memory location at offset
See if you can spot the grammatical (SYNTAX) er- 245AH in the data segment
rorsthe
in following instructions (use Chapter 6 to h. Decrements SP by one
help you): i. Rotates the most significant bit of AL into the
a. MOV BH. AX d. MOV 7632H, CX least-significant bit position
b. MOV DX, CL e. IN BL, 04H j. Copies DL to a memory location whose offset is
c. ADD AL, 2073H in BX
k. Masks the lower 4 bits of BL
1(1. Show the results that will be in the affected regis- /. Sets the most significant bit of AX to a one but
ters memory
or locations after each of the following
does not affect the other bits
groups of instructions execute. Assume that each m. Inverts the lower 4 bits of BL but does not af-
group of instructions starts with the register and
fect theother bits.
memory contents shown in Figure 3-15. (Use
Chapter 6.) 2. Construct the binary code for each of the following
a. ADD BL. AL SUB AL, CL 8086
808R instructions.
instructions.
MOV [0004], BL INC BX a. MOV BL. AL J- ROR AX. 1
b. MOV CL. 04 MOV [BX], AL b. MOV [BX], CX 9- OUT DX. AL
ROR DI. CL d ADD AL. BH c. ADD BX. 59H[DI] h. AND AL. OFH
c. MOV BX, 000AH DAA d. SUB [2048], DH i. NOP

MOV AL, [BX] e. XCHG CH. ES:[BX] j- IN AL, DX

70 CHAPTER THREE
13. Describe the function of each assembler directive 1?. Write the pseudocode representation for tli<- flow
and Instruction statement in the shorl program chart In Figure 3-14,
shown below these review problems.

14. Describe how an assembly language program is


developed and debugged using system tools such
as editors, assemblers, linkers, locators, emula-
tors, and
debuggers.

i pressure read p r o 3 r a m
DATA.HERE SEGMENT
PRESSURE DB 0 istorase for pressure
DATA_HERE ENDS
PRESSURE-PORT EOU 04H ipressure sensor connected