You are on page 1of 135

DISTANCE LEARNING CENTRE

AHMADU BELLO UNIVERSITY


ZARIA, NIGERIA

COURSE MATERIAL

FOR

Course Code &Title: COSC 204/ COMPUTER ORGANIZATION

AND ASSEMBLY LANGUAGE

Programme Title: B.Sc. COMPUTER SCIENCE

1
COPYRIGHT PAGE
© 2018 Ahmadu Bello University (ABU) Zaria, Nigeria

All rights reserved. No part of this publication may be reproduced in any


form or by any means, electronic, mechanical, photocopying, recording or
otherwise without the prior permission of the Ahmadu Bello University,
Zaria, Nigeria.

First published 2018 in Nigeria.

ISBN:

Published and printed in Nigeria by:


Ahmadu Bello University Press Ltd.
Ahmadu Bello University,
Zaria, Nigeria.

Tel: +234

E-mail:

2
COURSE WRITERS/DEVELOPMENT TEAM
Editor
Prof. M.I Sule

Course Materials Development Overseer


Dr. Usman Abubakar Zaria

Subject Matter Expert


Dr. Mustapha. A. Bagiwa

Subject Matter Reviewer


Mal. Nura Sulaiman

Language Reviewer
Enegoloinu Adakole

Instructional Designers/Graphics
Nasiru Tanko , Ibrahim Otukoya

Proposed Course Coordinator


Emmanuel Ekoja

ODL Expert
Dr. Abdulkarim Muhammad

3
COURSE STUDY GUIDE
i. COURSE INFORMATION
Course Code : COSC 204
Course Title: Computer Organization and Assembly Language
Credit Units: 3
Year of Study: 2
Semester: 2

ii. COURSE INTRODUCTION AND DESCRIPTION


Introduction:
This course is focused on teaching students the basic concepts of computer
organisation and assembly language programming. The course is aimed at
providing students with practical experience of how software is written in an
environment that teaches how a typical computer operates.

Description:
Introduction to the basic concepts of computer organisation. X86 processor
architecture. Assembly language fundamentals, Data transfer, Addressing mode
and arithmetic. Introduction to procedure and conditional processing.

iii. COURSE PREREQUISITES


COSC101 or Equivalent. You are also expected to have:
1. Satisfactory level of English proficiency
2. Basic Computer Operations proficiency
3. Online interaction proficiency

4
4. Web 2.0 and Social media interactive skills
iv. COURSE LEARNING RESOURCES
i. Course Textbooks
a. Irvine, Kip R., and Lyla B. Das. Assembly language for x86
processors. Prentice Hall, 2011.
b. Vincent P. Heuring, Harry F. Jordan, Computer System Design &
Architecture, Prentice Hall, 2004.
c. Dandamudi et al, Introduction to Assembly Language Programming:
From 8086 to Pentium, Springer, New York, 1998.

v. COURSE OBJECTIVES AND OUTCOMES


After studying this course, you should be able to:
1. Explain the basic concepts of machine language and data representation.
2. Explain in details the x86 processor architecture.
3. Write programs in assembly language.
4. Explain and make use of arithmetic instructions and Addressing mode in
assembly language.
5. Differentiate between data related operators and Directives in assembly
language.
6. Perform stack operations.
7. Define and use procedures and flowcharts.
8. Understand and use the Boolean and comparison instructions, conditional
jumps and loops, high-level logic structures.

vi. ACTIVITIES TO MEET COURSE OBJECTIVES


Specifically, this course shall comprise of the following activities:

5
1. Studying courseware
2. Listening to course audios
3. Watching relevant course videos
4. Field activities, industrial attachment or internship, laboratory or
studio work (whichever is applicable)
5. Course assignments (individual and group)
6. Forum discussion participation
7. Tutorials (optional)
8. Semester examinations (CBT and essay based).

vii. TIME (TO COMPLETE SYLABUS/COURSE)


To cope with this course, you would be expected to commit a minimum of 3 hours
weekly for the Course (study, assignments & Forum discussions).

viii. GRADING CRITERIA AND SCALE


Grading Criteria
A. Formative assessment
Grades will be based on the following:
Individual assignments/test (CA 1,2 etc) 20
Group assignments (GCA 1, 2 etc) 10
Discussions/Quizzes/Out of class engagements etc 10

B. Summative assessment (Semester examination)


CBT based 30
Essay based 30
TOTAL 100%

6
C. Grading Scale:
A = 70-100
B = 60 – 69
C = 50 - 59
D = 45-49
F = 0-44

D. Feedback
Courseware based:
1. In-text questions and answers (answers preceding references)
2. Self-assessment questions and answers (answers preceding references)

Tutor based:
1. Discussion Forum tutor input
2. Graded Continuous assessments

Student based:
1. Online programme assessment (administration, learning resource,
deployment, and assessment).

IX. LINKS TO OPEN EDUCATION RESOURCES


OSS Watch provides tips for selecting open source, or for procuring free or open
software.
SchoolForge and SourceForge are good places to find, create, and publish open
software. SourceForge, for one, has millions of downloads each day.

7
Open Source Education Foundation and Open Source Initiative, and other
organisation like these, help disseminate knowledge.
Creative Commons has a number of open projects from Khan
Academy to Curriki where teachers and parents can find educational materials for
children or learn about Creative Commons licenses. Also, they recently launched
the School of Open that offers courses on the meaning, application, and impact of
"openness."
Numerous open or open educational resource databases and search engines
exist. Some examples include:

 OEDb: over 10,000 free courses from universities as well as reviews of colleges
and rankings of college degree programmes
 Open Tapestry: over 100,000 open licensed online learning resources for an
academic and general audience
 OER Commons: over 40,000 open educational resources from elementary school
through to higher education; many of the elementary, middle, and high school
resources are aligned to the Common Core State Standards
 Open Content: a blog, definition, and game of open source as well as a friendly
search engine for open educational resources from MIT, Stanford, and other
universities with subject and description listings
 Academic Earth: over 1,500 video lectures from MIT, Stanford, Berkeley,
Harvard, Princeton, and Yale
 JISC: Joint Information Systems Committee works on behalf of UK higher
education and is involved in many open resources and open projects including
digitising British newspapers from 1620-1900!

Other sources for open education resources


Universities

 The University of Cambridge's guide on Open Educational Resources for Teacher


Education (ORBIT)

8
 OpenLearn from Open University in the UK
Global

 Unesco's searchable open database is a portal to worldwide courses and research


initiatives
 African Virtual University (http://oer.avu.org/) has numerous modules on subjects
in English, French, and Portuguese
 https://code.google.com/p/course-builder/ is Google's open source software that is
designed to let anyone create online education courses
 Global Voices (http://globalvoicesonline.org/) is an international community of
bloggers who report on blogs and citizen media from around the world, including
on open source and open educational resources
Individuals (which include OERs)

 Librarian Chick: everything from books to quizzes and videos here, includes
directories on open source and open educational resources
 K-12 Tech Tools: OERs, from art to special education
 Web 2.0: Cool Tools for Schools: audio and video tools
 Web 2.0 Guru: animation and various collections of free open source software
 Livebinders: search, create, or organise digital information binders by age, grade,
or subject (why re-invent the wheel?)

9
X. ABU DLC ACADEMIC CALENDAR/PLANNER

PERIOD
Semester Semester 1 Semester 2 Semester 3
Activity JAN FEB MAR APR MAY JUN JUL AUG SEPT OCT NOV DEC
Registration

Resumption

Late Registn.

Facilitation

Revision/
Consolidation
Semester
Examination

N.B: - All Sessions commence in January


- 1 Week break between Semesters and 6 Weeks vocation at end of session.
- Semester 3 is OPTIONAL (Fast-tracking, making up carry-overs & deferments)

10
XI. COURSE STRUCTURE AND OUTLINE
Course Structure
WEEK MODULE STUDY SESSION ACTIVITY
1. Read Courseware for the corresponding Study Session.
2. View the Video(s) on this Study Session
Study Session 1: 3. Listen to the Audio on this Study Session
Title: Basic Concepts of 4. https://www.youtube.com/watch?v=yIVXjl4SwVo
Week1 Computer Organization 5. View any other Video/U-tube(http://bit.ly/2TViEt2 , http://bit.ly/2UdpuyK ,
http://bit.ly/2HRHKr9 , http://bit.ly/2YKfaNm )
6. View referred OER(address/site)
7. View referred Animation (Address/Site)
8. Read Chapter/page of Standard/relevant text.
STUDY 9. Any additional study material
MODULE 10. Any out of Class Activity
1 1. Read Courseware for the corresponding Study Session.
2. View the Video(s) on this Study Session
Study Session 2: 3. Listen to the Audio on this Study Session
Week 2 Title: Processor 4. View any other Video/U-tube(http://bit.ly/2UuYPga , http://bit.ly/31mbTnU ,
Architecture http://bit.ly/2ZdvuJA , http://bit.ly/2UuYPga , http://bit.ly/2KHtZLW )
5. View referred OER(address/site)
6. View referred Animation (Address/Site)
7. Read Chapter/page of Standard/relevant text.
8. Any additional study material
9. Any out of Class Activity
1. Read Courseware for the corresponding Study Session.
2. View the Video(s) on this Study Session
Study Session 3 3. Listen to the Audio on this Study Session
Week3 Title: 4. View any other Video/U-tube(http://bit.ly/2UcFzF6 , http://bit.ly/2Zd252j ,
Basics of Assembly http://bit.ly/2Zd27XZ , http://bit.ly/2Z7szlR , http://bit.ly/2KFaweA ,
Language http://bit.ly/2H8BDg3 )
5. View referred OER(address/site)
6. View referred Animation (Address/Site)

11
7. Read Chapter/page of Standard/relevant text.
8. Any additional study material
9. Any out of Class Activity
1. Read Courseware for the corresponding Study Session.
2. View the Video(s) on this Study Session
Study Session 4 3. Listen to the Audio on this Study Session
Week4 Title: Arithmetical 4. View any other Video/U-tube (http://bit.ly/2UcFzF6 , http://bit.ly/2z40j4X ,
Instruction and Addressing http://bit.ly/2KH5fTQ , http://bit.ly/2Z9NeRZ , http://bit.ly/2Nf0VwM ,
Mode http://bit.ly/2PcVgds )
5. View referred OER (address/site )
6. View referred Animation (Address/Site)
7. Read Chapter/page of Standard/relevant
8. Any additional study material
9. Any out of Class Activity
1. Read Courseware for the corresponding Study Session.
2. View the Video(s) on this Study Session
3. Listen to the Audio on this Study Session
Week 5 Study Session 1 4. View any other Video/U tube (http://bit.ly/2UcFzF6 , http://bit.ly/2PdfRxU ,
Title: http://bit.ly/2Ng7sHq , http://bit.ly/31QCKsO )
Data-Related Operators 5. View referred OER(address/site)
and Directives 6. View referred Animation (Address/Site)
7. Read Chapter/page of Standard/relevant text.
8. Any additional study material
STUDY 9. Any out of Class Activity
MODULE
1. Read Courseware for the corresponding Study Session.
2 2. View the Video(s) on this Study Session
Study Session 2 3. Listen to the Audio on this Study Session
Week 6 Title: Interrupts and Stack 4. View any other Video/U-tube (http://bit.ly/2zdnIAJ , http://bit.ly/2KFQCQx ,
Operations http://bit.ly/2Hea19k , http://bit.ly/2UcFzF6 , http://bit.ly/2NczkfA )
5. View referred OER(address/site)
6. View referred Animation (Address/Site)
7. Read Chapter/page of Standard/relevant text.
8. Any additional study material
9. Any out of Class Activity

12
1. Read Courseware for the corresponding Study Session.
2. View the Video(s) on this Study Session
Study Session 3 3. Listen to the Audio on this Study Session
Title: 4. View any other Video/U-tube address/site (http://bit.ly/2UcFzF6 ,
Week7 Program Design using http://bit.ly/2MosQec , http://bit.ly/2Mqfgqu , http://bit.ly/31NTa4U ,
Procedures http://bit.ly/2z6nnzN )
5. View referred OER(address/site)
6. View referred Animation (Address/Site)
7. Read Chapter/page of Standard/relevant text.
8. Any additional study material
9. Any out of Class Activity

1. Read Courseware for the corresponding Study Session.


2. View the Video(s) on this Study Session
Study Session 4 3. Listen to the Audio on this Study Session
Week8 Title: 4. View any other Video/U-tube (http://bit.ly/2UcFzF6 , http://bit.ly/2NheZG0 ,
Flowchart http://bit.ly/2HaW9wj , http://bit.ly/2KQitwq , http://bit.ly/31P2mpW )
5. View referred OER(address/site)
6. View referred Animation (Address/Site)
7. Read Chapter/page of Standard/relevant text.
8. Any additional study material
9. Any out of Class Activity
1. Read Courseware for the corresponding Study Session.
Study Session 1 2. View the Video(s) on this Study Session
Title: 3. Listen to the Audio on this Study Session
Week 9 Boolean and Comparison 4. View any other Video/U-tube (http://bit.ly/2UcFzF6 , http://bit.ly/2z8oX4h ,
Instructions http://bit.ly/2P46aCa , http://bit.ly/2THnBHk )
5. View referred OER(address/site)
6. View referred Animation (Address/Site)
7. Read Chapter/page of Standard/relevant text.
STUDY 8. Any additional study material
MODULE 9. Any out of Class Activity
3
1. Read Courseware for the corresponding Study Session.
2. View the Video(s) on this Study Session
Study Session 2 3. Listen to the Audio on this Study Session
Week 10

13
Title: 4. View any other Video/U-tube (http://bit.ly/2UcFzF6 , http://bit.ly/2NgMSqu ,
Conditional Jumps http://bit.ly/2TIsuzI , http://bit.ly/2zbmg21 , http://bit.ly/2ZeoyrI ,
http://bit.ly/2ZeoyrI )
5. View referred OER(address/site)
6. Read Chapter/page of Standard/relevant text.
7. Any additional study material
8. Any out of Class Activity
1. Read Courseware for the corresponding Study Session.
2. View the Video(s) on this Study Session
3. Listen to the Audio on this Study Session
Week 11 Study Session 3 4. View any other Video/U-tube (http://bit.ly/2UcFzF6 , http://bit.ly/2ZeoyrI ,
Title: http://bit.ly/2ZeoyrI , http://bit.ly/2TKTQpa , http://bit.ly/2Z6QMc3 )
Conditional Loop 5. View referred OER(address/site )
Instructions 6. View referred Animation (Address/Site)
7. Read Chapter/page of Standard/relevant text.
8. Any additional study material
9. Any out of Class Activity
1. Read Courseware for the corresponding Study Session.
2. View the Video(s) on this Study Session
Study Session4 3. Listen to the Audio on this Study Session
Week 12 Title: 4. View any other Video/U-tube (http://bit.ly/2UcFzF6 , http://bit.ly/2Z6QMc3 ,
Conditional Structures http://bit.ly/30gGR0M , http://bit.ly/2NgMSqu , http://bit.ly/2NgMSqu ,
http://bit.ly/2P47VPM ,)
5. View referred OER(address/site)
6. View referred Animation (Address/Site)
7. Read Chapter/page of Standard/relevant text.
8. Any additional study material
9. Any out of Class Activity
Week 13 REVISION/TUTORIALS (On Campus or Online)& CONSOLIDATION WEEK

Week 14 & 15 SEMESTER EXAMINATION

14
15
Course Outline
MODULE 1:
Study Session 1: Basic Concepts of Computer Organisation
Study Session 2: Processor Architecture
Study Session 3: Basics of Assembly Language
Study Session 4: Arithmetical Instructions and Addressing Modes

MODULE 2:
Study Session 1: Data-Related Operators and Directives
Study Session 2: Interrupts and Stack Operations
Study Session 3: Program Design Using Procedures
Study Session 4: Flowchart

MODULE 3:
Study Session 1: Boolean and Comparison Instructions
Study Session 2: Conditional Jumps
Study Session 3: Conditional Loop Instructions
Study Session 4: Conditional Structures

16
CONTENTS
Title Page…………………………………………………………….…………………………...1
Copyright Page………………………………………………………..…………………………2
Course Writers/Development Team……………………………………………………………3
COURSE STUDY GUIDE……...……... ……………………………………………………….4
i. Course Information…………………………………………………………………4
ii. Course Introduction and Description……………………………………………...4
iii. Course Prerequisites………………………………………………………………...4
iv. Course Learning Resources…………………………………………………………5
v. Course objectives and outcomes……………………………………………………5
vi. Activities to meet Course Objectives……………………………………………….5
vii. Time (To complete Syllabus/Course)………………………………………………6
viii. Grading criteria and Scale………………………………………………………….6
ix. Links to open education resources………………………………………………….7
x. ABU DLC ACADEMIC CALENDAR/PLANNER………………………………10
xi. Course Structure and Outline……………………………………………………..11
xii. Contents …………………………………………………………………………….17
xiii. STUDY MODULES ……………………………………………………………….19
MODULE 1: ……………………………………………………………………………19
Study Session 1: Basic Concepts of Computer Organisation……………………………19
Study Session 2: Processor Architecture ………………………………………………..34
Study Session 3: Basics of Assembly Language………………………………………...43
Study Session 4: Arithmetical Instructions and Addressing Modes ……………………55

MODULE 2: …………………………………………………………………………..66
Study Session 1: Data-Related Operators and Directives……………………………….66
Study Session 2: Interrupts and Stack Operations ……………………………………...76
Study Session 3: Program Design Using Procedures …………………………………...82
Study Session 4: Flowchart ……………………………………………………………..89

MODULE 3: ……………………………………………………………………………95
Study Session 1: Boolean and Comparison Instructions ………………………………..95
Study Session 2: Conditional Jumps… ………………………………………………105

17
Study Session 3: Conditional Loop Instructions………………………………………117
Study Session 4: Conditional Structures………………………………………………122

xiv. GLOSSARY ……………………………………………………………………132

18
STUDY MODULES
MODULE 1:
Contents:
Study Session 1: Basic Concepts of Computer Organisation
Study Session 2: Processor Architecture
Study Session 3: Basics of Assembly Language
Study Session 4: Arithmetical Instructions and Addressing Modes

STUDY SESSION 1
Basic Concepts of Computer Organisation
Section and Subsection Headings:
Introduction
1.0 Learning Outcomes
2.0Main Content
2.1-Virtual Machines Concept
2.2-Data representation
2.2.1-Binary Numbers
2.3- Translating between binary and decimal
2.4-Binary Addition
2.5-Integer Storage Sizes
2.6-Hexadecimal Numbers
2.6.1- Translating between decimal and hexadecimal
2.6.2-Hexadecimal Addition
2.6.3-Hexadecimal subtraction
2.7-Signed Integers
2.7.1-Binary subtraction
2.8-Boolean operations

19
3.0 Tutor Marked Assignments (Individual or Group assignments)
4.0 Study Session Summary and Conclusion
5.0 Self-Assessment Questions and Answers
6.0 Additional Activities (Videos, Animations & Out of Class activities)
7.0 References/Further Readings

Introduction:
You are welcome to the basic concepts of computer organisation study session. In
this study session, I will introduce you to the key concepts that are related to
computer organisation, which includes the virtual machine concepts, number
systems (decimal, binary, hexadecimal). Binary addition, 2’s complements, binary
subtraction, hexadecimal addition and subtractions and Boolean operations.

1.0 Study Session Learning Outcomes


After studying this session, I expect you to be able to:
1. Explain the virtual machine concept
2. Convert numbers from one base to another
3. Explain the fundamental Boolean operations

2.0Main Content
2.1 Virtual Machines Concept
A simple way to explain the relationship between a hardware and software of a
computer is referred to as the virtual machine concept. In the early computers,
programs are written for specific computers using its native machine language L0
where each instruction in the program is simple and can be executed with a few
number of electronic circuits. However, as time passes by, programmers tend to
have difficulty writing the same programs in variety of different ways for different
computers. Moreover, writing these kind of programs is solely based on numbers
and does require the detailed knowledge of the architecture of a given computer.

20
One solution to this problem is to devise a new language L1 for program writing,
which is easier to use. There are two ways to achieve this:
1. Interpretation: As the L1 program is running, each of its instructions could
be decoded and executed by a program written in language L0. The L1
program begins running immediately, but each instruction has to be decoded
before it can execute.
2. Translation: The entire L1 program could be converted into an L0 program
by an L0 program specifically designed for this purpose. Then the resulting
L0 program could be executed directly on the computer hardware.
Instead of using only languages, it is easier to think in terms of a hypothetical
computer, or virtual machine, at each level. A virtual machine also known as an
image is software that emulates the behaviour of a physical computer running an
operating system and other system applications. The virtual machine VM1, as we
will call it, can execute commands written in language L1. The virtual machine
VM0 can execute commands written in language L0:

Question 1: What is a virtual Machine?


Answer: A virtual machine also known as an image is software that emulates the behaviour of a
physical computer running an operating system and other system applications
2.2 Data Representation
A computer programmer that uses assembly language deal with data that reside at
the storage level of a physical computer, as such this kind of programmer need to
quite often examine memory and registers. Different types of numerals are used to
represent data in a computer memory. In this section, we will be learning different
number numerals that are used to represent quantities in a computer such as binary,
decimal and hexadecimal number representations.

2.2.1 Binary Numbers

21
Data in a computer memory is stored as a combination of 0s and 1s called the binary
numbers. Binary numbers are numbers in base two such that a binary digit can
either be a 0 or 1. Each binary digit is called a bit. Bits are numbered starting at 0
from left to right. The first bit from the left is called the most significant bit (MSB)
and the first bit from the right is called the least significant bit (LSB) as shown in
Figure 1.1.1.

MSB LSB
1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1
15 0
Figure 1.1.1: example 1 of binary number representation

Binary numbers can be either signed or unsigned. A signed binary number is


either positive or negative. An unsigned binary number is by default positive. Zero
is considered positive. Starting with the LSB in the binary number system, each
digit represents an increasing power of 2 as shown in Figure1.1.2.

1 1 1 1 1 1 1 1

Figure1.1.2: example 2 of binary number representation

Question 2: What is a signed binary number?


Answer: A signed binary number is a binary number that is either positive or negative

2.3 Translating Between Unsigned Binary to Decimal


The conversion of binary number system to decimal number system is an essential
idea to comprehend as a base for digital computer systems. This conversion can be
possible in various ways. One of this ways is by utilising weighted columns to
recognise the order of the binary digits in order to decide the value of the number in
decimal notation. For example, consider an unsigned binary integer having n digits.
Therefore, the decimal value represented by of the unsigned binary integer will be
given as:

22
Where D represent a binary digit.

Example 1: Convert 11010010 in binary to decimal.


Solution

Binary Number 1 1 0 1 0 0 1 0
Power of 2

(1
(1
(1

210

Therefore, the decimal equivalent of the binary digits =


We have learnt the way to convert binary to decimal numbers. We will now learn
how to convert decimal to binary. A simple technique that is used for converting
decimal to its binary equivalent is to use the repeated division by 2 methods.
Hence, we continually divide the decimal number by 2 (two) to get a result and a
remainder of either a “1” or a “0” until the end result equals zero.
Example 2: Convert 210 in decimal to binary.

Solution
Division by 2 Quotient Remainder Bit Number
105 0 0
52 1 1
26 0 2
13 0 3
6 1 4
3 0 5
1 1 6
0 1 7

Therefore, the binary equivalent of the decimal digit =


Question 3: Convert 10010110 in binary to decimal.
Answer: 150

2.4 Binary Addition

23
Binary addition takes after the same fundamental rules as for the normal decimal
addition. However, binary addition results in only two digits with the highest digit
being “1”. So when adding two binary numbers, a carry out is created when the
result of the addition is greater than or equals to 2. Hence, this gets to be a
“CARRY” bit. As an example, consider the single bit addition in Figure1.1.3:

Figure1.1.3: example of single bit addition

Thus, when adding numbers in binary, we start with the LSB, add each pair of
digits, and include the carry if present.
Example 3: Find the sum of

Solution
Carry 1
0 0 0 0 0 1 0 0 (4)
+ 0 0 0 0 0 1 1 1 (7)
0 0 0 0 1 0 1 1 (11)

Question 4: Find the sum of


Answer: =374

2.5 Integer Storage Sizes


The storage capacity unit for all data in an x86 computer is a byte, which contains
8 bits. Other capacity sizes are word containing 2 bytes, double word containing 4
bytes and Quad word containing 8 bytes). This is shown in the Figure1.1.4:

Byte 8
Standard Word 16
sizes Double
word 32
Qaudword 64
Figure 1.1.4: Integer storage sizes

Question 5: How many bytes are contained in a double word?

24
Answer: four bytes

2.6 Hexadecimal Numbers


A hexadecimal number or simply Hex is the grouping of base 2 numbers into sets
of four thereby permitting the translation of 16 distinctive base two digits. An
example of how a binary number 1010011110000100 is translated in hexadecimal
is shown in Figure1.1.5:
1010 0111 1000 0100
A 7 8 4
Figure1.1.5: Translating binary numbers to hexadecimal numbers

The hexadecimal uses a base 16 number system and is well known for choice for
representing base two numbers since their arrangement is compact and easier to
understand as compared to the length base two digits comprising of 0s and 1s.
Hexadecimals are made up of numbers from 0 to 15 making 16 possible digits.
These numbers are shown in Figure1.1.6:

Figure 1.1.6: Hexadecimal number representation

Question 6: What base number system is used by the Hexadecimal?


Answer: Base 16

2.6.1 Translating between decimal to hexadecimal

25
The conversion of hexadecimal number system to decimal number system can also
be possible in various ways. One of these ways is by utilising weighted columns to
recognise the order of the hexadecimal digits in order to decide the value of the
number in decimal notation. For example, consider an unsigned hexadecimal integer
having n digits. Therefore, the decimal value represented by of the unsigned
hexadecimal integer will be given as:

Where D represent a binary digit.

Example 4: Convert 136A in hexadecimal to decimal.


Solution

Hex 1 3 6 A

Power of 16

=(
=

= 4970
Therefore, the decimal equivalent of the hexadecimal digit=
We have learnt the way to convert hexadecimal to decimal numbers. We will now
learn how to convert decimal to hexadecimal. A simple technique that is used for
converting a decimal to its hexadecimal equivalent is to use the repeated division
by 16. Hence, we continually divide the decimal number by 16 (Sixteen) to get a
result and a remainder until the end result equals zero.
Example 5: Convert 4970 in hexadecimal to decimal.
Solution
Division by 2 Quotient Remainder Bit Number
310 A 0
19 6 1
1 3 2
0 1 3

26
Therefore, the hexadecimal equivalent of the decimal digit =

Question 7: Convert 4786 in decimal to hexadecimal.


Answer: 12B2

2.6.2 Hexadecimal Addition


Hexadecimal addition takes after the same fundamental rules as the normal
decimal addition. However, hexadecimal addition results in 16 digits with
the highest digit being “F” and the lowest digit being “0”. So when adding two
hexadecimal numbers, a carry out is created when the result of the addition is
greater than or equals to 16. Thus, we divide the resulting sum of the two
hexadecimal digits by 16, the quotient becomes the carry value and the remainder
becomes the sum. Thus, when adding numbers in hexadecimal, we start with the
LSB, add each pair of digits, and include the carry if present.
Example 6: Find the sum of
Solution
1
9 A
+ 4 B
E 5 (11)

Question 8: Find the sum of 8AB and B78 in hexadecimal.


Answer: 1423

2.6.3 Hexadecimal subtraction


Hexadecimal subtraction takes after the same fundamental rules as the normal
decimal subtraction. However, hexadecimal subtraction results in only 16 digits
with the highest digit being “F” and the lowest being “0”. So when subtracting two
hexadecimal numbers, borrowing might be needed when a value called subtrahend

27
is greater than the value to subtract from called minuend. Hence, this gets to be a
“BORROW”. If such borrow is required from the next digit to the left, add 16
(decimal) to the current digit's value.
Example 7: Find the difference of
Solution

5 16+4 =20
__ B 5 6 4 Minuend
A 1 3 6 Subtrahend
The difference of is 1 4 2 E Difference

Question 9: Subtract B78 from 8AB in hexadecimal.


Answer: 2CD

2.7 Signed Binary Integers


A signed binary number is either positive or negative. In principle, a signed
number is used for encoding negative binary numbers in a computer. A sign bit is
used to represent the sign of the number. In x 86 processor computers, MSB is
used to represent, the sign of a number where zero indicates a positive number and
a 1 indicates a negative number. See example below
Example 7

MSB = Sign Bit

1 0 1 1 1 1 1 1

Question 10: In signed number representation, which bit is used to represent the sign?
Answer: MSB

2.7.1 Binary subtraction


Negative binary numbers uses the 2’s complement representation. This satisfies an

28
additive inverse property. 2’s complement representation is useful to processor
designers because it eliminate the need for a separate circuit for addition and
subtraction. The rules for binary subtraction using the 2’s complement are:
i. Reverse the binary bit of the subtrahend
ii. Add on to the value you have reversed
iii. The sum is the 2’s complement of the initial value
iv. Add the 2’s complement to the minuend to get the result of the subtraction.
Example 8: Subtract 0101 from 1001
Solution
1 0 0 1
0 1 0 1

In order to solve this subtraction problem, we first convert 0101 to its 2’s
complement representation.
Step 1: Reverse the bits.
Therefore, 0101 become 1010
Step 2: Add one to the reversed bits
1 0 1 0
+ 0 0 0 1
1 0 1 1
Hence, the 2’s complement of 0101 is 1011
Step 3: Add the 2’s complement to the minuend to get the result of the subtraction.
1 0 0 1
1 0 1 1
0 1 0 0

The result of the Subtraction of 0101 from 1001 is 0100

2.8 Boolean Operations


Boolean algebra is based on symbolic logic designed by a Mathematician George
Boole in the mid nineteenth century. Boolean algebra was found to be an asset for

29
the design of digital circuits. Each Boolean expression is created from one or more
of the following operators in Figure1.1.7:

Figure 1.1.7: Boolean Operators

The NOT operator reverses the value of a Boolean operator as shown in a truth
table in Figure1.1.8:

Figure 1.1.8: NOT Boolean Operator truth table

The AND operator act on two or more variable and only evaluates to see if all
variables are true. This is shown in a truth table in Figure1.1.9.

Figure 1.1.9: AND Boolean Operator truth table

30
The OR operator act on two or more variable and only evaluates to true if one of
the variables or all the variables are true. This is shown in a truth table in Figure
10.

Figure 1.1.10: OR Boolean Operator truth table

It is worth noting that Boolean operators have precedence just like arithmetical
operators. Figure1.1.11 shows the Boolean operator precedence

Figure 1.1.11: Boolean operator precedence

3.0 Tutor Marked Assignments (Individual or Group)


1. Explain why programmers find it difficult to write programs in machine
language.
2. What do you understand by a least Significant Bit (LSB)?
3. If a Boolean function has three inputs, how many rows are required for its
truth table?

31
4.0 Conclusion/Summary
At the end of this session, we have studied the introductory section of machine
language and Data representation. In the next study session, you will be learning
the general description of a microcomputer design, the instruction execution cycle,
the concept of memory management and a description on the components of a
microcomputer.

5.0 Self-Assessment Questions and Answer


Questions
1. In what form are numbers stored and transmitted inside a computer
2. What is the binary representation of the decimal number 127?
3. What is the decimal representation of the four bit number 0111?
4. What is the minimum number of bit required to store the hexadecimal
number FF?

6.0 Answers to Self-Assessment Questions


1. Binary form
2. 1111111
3. 7
4. 8 bits

7.0 Additional Activities (Videos, Animations & Out of Class activities) e.g.
a. Visit U-tube add http://bit.ly/2TViEt2 , http://bit.ly/2UdpuyK ,
http://bit.ly/2HRHKr9 , http://bit.ly/2YKfaNm. Watch the video & summarise in 1
paragraph
b. View the animation on add/site and critique it in the discussion forum
c. Take a walk and engage any 3 students on Basic Concepts of Computer
Organization; In 2 paragraphs summarise their opinion of the discussed topic. etc.

32
8.0 References/Further Readings
1. Irvine, Kip R., Assembly Language for x86 Processors, 7th Edition.
Pearson, 2014. ISBN-13: 9780133769401 ISBN-10: 0133769402,
2. Hennessy, J. L, and Patterson, D. A., Computer Architecture: A Quantitative
Approach, 5th Edition. Morgan Kaufmann, 2011. ISBN-13 : 978-
0123838728 ISBN- 10 : 012383872X

33
STUDY SESSION 2
Processor Architecture
Section and Subsection Headings:
Introduction
1.0 Learning Outcomes
2.0 Main Content
2.1-General description of a microcomputer design
2.2-Instruction execution cycle
2.3-Memory Management
2.4-Components of a Microcomputer
3.0 Tutor Marked Assignments (Individual or Group assignments)
4.0 Study Session Summary and Conclusion
5.0 Self-Assessment Questions and Answers
6.0 Additional Activities (Videos, Animations & Out of Class activities)
7.0 References/Further Readings

Introduction:
You are welcome to yet another study session in computer organisation and
assembly language course. In this study session, you will be learning about the
general description of a microcomputer design, the instruction execution cycle, the
concept of memory management and a description on the components of a
microcomputer.

1.0 Study Session Learning Outcomes


After studying this session, I expect you to be able to:
1. Explain the architecture of a microcomputer
2. Explain the different step of instruction cycle
3. Explain the concept of memory management

34
2.0 Main Content
2.1 General Description of A Micro-Computer Design
A computer is an electronic device that accept data as input process that data and
produced output in human readable form. A simple computer is made up of four
basic components namely: the Input unit, the storage unit, the central processing
unit and the output unit. The basic organisation of a computer system is shown in
Figure 1.2.1:

Storage

Input Unit Output Unit

Control Unit

Arithmetical Central Processing Unit


and Logical
Unit

Figure1.2.1: Basic Organisation of a computer

Data and instructions must enter in to the computer system using the input unit
before any processing can be performed on that data. Example of an input unit is
the keyboard, scanners, microphones etc. The output unit supply the result of
computation in a computer to the outside world in a meaningful format. Example
of an output unit is the monitors, printers etc. The storage unit holds in data and

35
instructions that is entered through the input unit to be processed. Example of
storage units are the floppy disk, secured hard disk, CD drives. Pen drives etc. The
central processing unit (CPU) is the main unit inside the computer responsible for
all events inside the computer. It controls all internal and external devices of the
computer, making it the brain of any computer. The central processing unit is
further classified in to the arithmetical and logical unit (ALU) and the control unit
(C.U). The arithmetical and logical unit is responsible for arithmetical operations
such as addition, subtraction, multiplication etc. it is also responsible for logical
operations such as comparisons. The control unit directs and controls the activities
of the external devices of a computer system. It interprets the instructions fetched
into the computer and determines what data if any are needed.

In-text Question 1: What is a computer?


Answer: A computer is an electronic device that accept data as input process that data and
produced output in human readable form.

2.2 Instruction Execution Cycle


The central processing unit is made up of smaller components that work together
for program execution. These components are program counter (PC), the
instruction register (IR), the memory address register (MAR), the memory buffer
register (MBR), the input output address register (I/O AR), the input output buffer
register (I/O BR) and the execution unit. Other models that are associated with
program execution are the main memory and the input output model. This is
shown in the Figure 1.2.2. The program counter stores the address of the next
instruction to be executed. The MAR stores the address value of the program to be
executed. This address will be used for data transfer and data storage. The MBR
transfer data from the CPU to main memory and from the main memory to the
CPU. The IR stores the instruction to be executed.

36
CPU

PC MAR
Main Memory

MBR
IR

I/O AR

Execution
Unit I/O BR

Input Output Module

Figure1.2.2: The central processing unit

The instruction execution cycle consist of five basic steps namely: the instruction
fetch, the instruction decode, the operand fetch, execution and operand
storage. In the first step, the value in the PC will be transferred to the MAR. The
MAR locates the address of the instruction from the main memory and transfers it
to the IR. In the second step, instruction decode divides the instruction into
operand and operation. In step three, operands will be fetched from the main
memory using the address placed in the MAR. Once the operands are fetched, they
are transferred to the MBR and finally to the execution unit. In the fourth step, the
execution takes both the operation and data for processing. In the final step, the
output generated by the execution unit is stored back into the main memory.

In-text Question 2: What is the function of a program counter?


Answer: The program counter stores the address of the next instruction to be executed.

37
2.3 Memory Management
Multiple machine cycles are required when reading data from memory thereby
requiring a great deal of time for one machine cycle. This is because memory
responds much more slowly than the CPU. A machine cycle is the time taken to
complete a single operation. One way to reduce the amount of time spent reading
and writing memory is to store the most recently used instructions and data in
high-speed memory called cache. The cache is a high speed RAM both inside and
outside the CPU. It is the fastest memory location that can be accessed directly by
the CPU.The access for the cache memory is random. There two levels of cache
memory namely: level 1 and level 2. Level 1 cache is found inside the CPU while
Level 2 cache is found outside the CPU. If the CPU finds a data it’s looking for
inside the cache memory, it is called a cache hit while if the CPU tries to find a
data in cache memory and the data is not there, this thus called a cache miss. A
cache can have a single or multi-level organisation. This is shown in Figure1.2.3
and 1.2.4 respectively

CPU Cache Main Memory

Figure 1.2.3: Single level cache organization

CPU Cache 1 Cache 2 Main Memory

Figure 1.2.4: Multi level cache organization

Furthermore, most operating systems now support what is referred to as paging in


order to aid memory management with the CPU. It is worth noting that the sum of
all programs can be larger than physical memory in a computer. Therefore, in
order to run such a program, the program is segmented into 4096-byte blocks
called pages so that part of the running program is in memory and others in disks.
The virtual memory manager in the operating system is responsible moving pages

38
in and outside the CPU. A page fault is created by CPU when a page must be
loaded from the disk.
In-text Question 3: What is a machine cycle?
Answer: A machine cycle is the time taken to complete a single operation.

2.4 Components of a Microcomputer


The physical most important components of a microcomputer are the motherboard,
video output, memory and the input-output ports. While the CPU is referred to as,
the brain of a computer, the motherboard or the main board of a computer is its
backbone. It contains a number of slots for interfacing with other devices. A
motherboard is the largest printed circuit board inside a computer covered in slots,
connector and chips. It has no processing power on its own but relies on other
component such as the CPU or GPU, which are sometimes docketed in to the
motherboard or soldered on to the motherboard. A diagrammatical representation
of a motherboard is shown in Figure1.2.5.

39
Figure1.2.5: Motherboard

In order for a signal from a DVD player, computer, or any other video source to a
display such as a TV or monitor, we need the video output component. The video
output is made up of the video controller and the video RAM. The video controller
can be found on the motherboard or inserted on to the motherboard as an
expansion card. The primary function of the video controller is to generate graphic
information to any video display device, such as a monitor or projector. They are
also known as graphics or video adapters. An example of a video controller is
shown in Figure1.2.6.

40
Figure1.2.6: Video Adapter

The Video RAM is a buffer that sits between a computer processor and a display.
It is used to store image data for a computer display. There are a number of input
outputs in a physical computer. Examples of these input output ports are the USB,
Ethernet, VGA, HDMI, Bluetooth etc. The USB stand for universal serial port and
can be found on computers, gaming consoles, TVs DVDs etc. The Ethernet port
allows one to plug an Ethernet cable, which can connect your computer to the
network and to the internet. The VGA port is used to connect the CPU to a display
monitor. The HDMI port is also used to the CPU to a display monitor. It is digital
with the ability to carry audio and can be found in most modern computers these
days. The Bluetooth is used to connect devices to a computer using wireless
connection. Bluetooth is used for small amounts of data transfer, covers only short
distances. However, Bluetooth has the disadvantage of low power usage.

In-text Question 4: What is the function of a video controller that can be found on a
motherboard?
Answer: The primary function of the video controller is to generate graphic information to any
video display devices, such as a monitor or projector.

3.0 Tutor Marked Assignments (Individual or Group)


1. Explain the basic step for instruction execution cycle?
2. With the aid of a diagram, differentiate between single level cache
organisation and multi-level cache organisation?
3. What is the basic function of the HDMI port?

41
4.0 Conclusion/Summary
At the end of this session, we have studied the description of a microcomputer
design, instruction execution cycle, introduction to memory management and the
components of a microcomputer. In the next study session, you will be learning the
basics of assembly language programming, which includes data type, variable
declaration, arrays, operand types, data transfer, comments and the 8086 assembly
language program template.

5.0 Self-Assessment Questions and Answers


Questions
1. Which part of the computer is directly involved in executing the instructions
of a computer program?
2. What is a cache?
3. What is cache hit?

6.0 Answers to Self-Assessment Questions


1. Processor
2. Cache is a high speed RAM both inside and outside the CPU.
3. Cache hit is a situation whereby the CPU finds a data it’s looking
for inside the cache memory.

7.0 Additional Activities (Videos, Animations & Out of Class activities) e.g.
a. Visit U-tube add http://bit.ly/2UuYPga , http://bit.ly/31mbTnU ,
http://bit.ly/2ZdvuJA , http://bit.ly/2UuYPga , http://bit.ly/2KHtZLW. Watch the
video & summarise in 1 paragraph
b. Take a walk and engage any 3 students on Processor Architecture; In 2
paragraphs summarise their opinion of the discussed topic. etc.

42
8.0 References/Further Readings
Irvine, Kip R., Assembly Language for x86 Processors, 7th Edition. Pearson, 2014.
ISBN-13: 9780133769401 ISBN-10: 0133769402,
Hennessy, J. L, and Patterson, D. A., Computer Architecture: A Quantitative
Approach, 5th Edition. Morgan Kaufmann, 2011. ISBN-13 : 978-
0123838728 ISBN- 10 : 012383872X

43
STUDY SESSION 3
Basics of Assembly Language
Section and Subsection Headings:
Introduction
1.0 Learning Outcomes
2.0 Main Content
2.1 - Introduction
2.2 - Data Type and Variable Declaration
2.3 - Arrays
2.3.1 - Array Declaration Using DUP
2.3.2 - Empty Array Declaration
2.4 - Operand Types
2.5 - Data Transfer
2.6 - Comments
2.7 - 8086 Assembly language program template
3.0 Tutor Marked Assignments (Individual or Group assignments)
4.0 Study Session Summary and Conclusion
5.0 Self-Assessment Questions and Answers
6.0 Additional Activities (Videos, Animations & out of Class activities)
7.0 References/Further Readings

Introduction:
You are welcome to the basics of assembly language study session .In this study, I
will introduce you to the basics of assembly language programming which includes
data type, variable declaration, arrays, operand types, data transfer, comments and
the 8086 assembly language program template.

44
1.1 Study Session Learning Outcomes
After studying this session, I expect you to be able to:
1. List and explain different types of CPU registers
2. Declare variable of different data type in assembly language
3. Declare arrays and access elements in an array
4. Perform different data transfer

2.0 Main Content


2.1 Introduction
Assembly language is a low level programming language that is easy to learn if
you focus and master its concept. There are several reasons why the study of
assembly language is important. Here are just three of them.1. The knowledge of
assembly language will improve our algorithmic and coding skills. 2. Assembly
language will introduce us to the knowledge of low-level language. 3. We use it to
understand how hardware’s interact with each other.
The central processing unit is made up of different type of registers. A register is a
named memory location inside a CPU that is optimised for speed. These registers
can be divided into general-purpose registers and segment registers. A 32-bit 8086
computer has eight general-purpose registers and these register are used for data
movement and arithmetical operations. This is shown in Table 1.3.1.
Table 1.3.1: 32 bit general purpose registers
32 Bit General Purpose Registers
Register Mnemonic Register Name
EAX Accumulator Register
EBX Base Register
ECX Counting Register
EDX Data Register
EBP Base Pointer
ESP Stack Pointer
45
ESI Source Index Register
EDI Destination Index Register

These general-purpose registers (EAX, EBX, ECX, and EDX) are 32 bits made up
of two 16-bit registers. Furthermore, each 16-bit register can be further sub-
divided into two 8-bit register namely a higher and a lower level register. This
shown in Figure1.3.1:

8 8
8 bits+8
AH AL bits
AX 16 bits
EAX 32 bits
Figure1.3.1: Components of a 32-bit EAX general-purpose registers

Example 1: If where b means binary


Then

The rest of the general-purpose registers (EBP, ESP, ESI, and EDI) sometimes
also referred to as index and base registers only have 16 bits for their lower half.
This shown in Table 1.3.3:
Table 1.3.2: Index and base registers
32 Bit General Purpose Registers
32 Bit Index and Base 16 Bit Index and Base
Registers Registers
EBP BP
ESP SP
ESI SI

46
EDI DI

A 32 bit 8086 computer has four segment registers as shown in Table 1.3.3.
Table 1.3.3: 32 bit segment registers
16 Bit Segment Registers
Register Mnemonic Register Name Function
CS Counting Segment Points to the segment
Register containing the current
program
DS Data Segment Register Generally points to
segment where
variables are defined
ES Extra Segment This register is left for
Register the programme to
define its usage
SS Stack segment Points to the segments
Register that contains the stack

In-text Question 1: What is a CPU register?


Answer: A registers is a named memory location inside a CPU that are optimized for speed.

2.2 Data Type and Variable Declaration


A variable in any program is a memory location that is given a name and can be
referenced during programming. Consider the below variable declaration in Java:

int x = 10;
double y = 20.0;

47
The first line interpret x is a name of a variable of type integer and has a value 10 and
second line interprets y as a variable of type double and has a value 20.0. Similarly,
we can also declare variable in 8086 assembly language. In 8086 assembly language,
we have four data types namely: DB, DW, DD and DQ. DB stand for Data Byte and is
used to define a data byte, DW stands for Data Word and is used to define data word,
DD stand for Double Data and is used to define a double word and DQ defined quad
word. Variables are defined using a general syntax as below:

Variable_ Name Type value

Example 2
A DB 9
Message DB ‘Hello World’

In the above example, a data byte memory is allocated for each character

Example 3
var DW 1122H

Characters in assembly language are enclosed in either a single or double quotation


marks and each character occupies a single byte.

Example 4
Enclose character in a single or double quotes
‘A’
“x”
Enclose strings in single or double quotes
“ABC”

48
‘xyz’
Each character occupies a single byte
Embedded quotes:
‘Say “Goodnight,” Gracie’

2.3 Arrays
An array in programming refers to the collection of objects which are of the same data
type and size. Each object in the array is called an array element. The general syntax
for an array definition in assembly language is:

Name Type Value


Example 5

a DB 1h,2h,35Fh,7Fh
b DW 1111h,2222h,3333h

The values of an array in assembly language that can be accessed using their index
numbers just like high-level languages.

Example 6

a DB 22h,23h,24,25h

a[0] a[1] a[2] a[3]


22 23 24 25

2.3.1 Array Declaration Using DUP


49
DUP stands for duplicate and used for array declaration. The DUP is used to duplicate
what a number passes to it as parameter a given number of times.
Example 7
Y DB 4 DUP(5)
This is similar to Y DB 5,5,5,5

M DB 2 DUP(3,4)
This is similar to M DB 3,4,3,4

2.3.2 Empty Array Declaration


An 8086 assembly language allows the declaration of an empty array the DUP
operator. The general syntax for the declaration of the empty array is

Name Type DUP

Example 7

var DB 10 DUP(?)
This is means the assembler will create an array called var of type data byte with 10
spaces and all initialised to zero.

In-text Question 2: Differentiate between a simple variable and an array variable.


Answer: A variable is a memory location that is give a name and can be referenced during
programming while an array refers to the collection of objects which are of the same data type and
size.

2.4 Operand Types


The 8086 assembly language program has three different operand types namely: the
immediate value, the register and the memory. The immediate value is referred to any
constant integer of 8, 16 or 32 bits. The register refers to the CPU registers. The

50
memory refers a reference to a location in the main memory.

In-text Question 3: What is an immediate value in assembly language?


Answer: The immediate value is referred to any constant integer of 8, 16 or 32 bits.

2.5 Data Transfer


Data transfer in 8086 assembly language is performed using the move (MOV)
instruction. The mov instruction is used to copy second operand called source to the
first operand called destination.

Example 8
mov eax, 7h

In this example, the second operand, which is an immediate value 7h, is copied to a
destination operand, which is register eax. However, the move instruction have certain
constraints it has to follow in terms of operands. The constraints are:
 mov register, memory | This is a valid move
 mov memory,register | This is a valid move
 mov register, register | This is a valid move
 mov memory, immediate value |This is a valid move
 mov register, immediate value |This is a valid move
 mov memory, memory |This is an invalid move

Example 9
 mov eax,test |mov register, memory
 mov test,bx |mov memory,register
 mov bx,cx |mov register, register
 mov test,7h |mov memory, immediate value

51
 mov eax, 0001b mov register, immediate value
 mov test, hello |mov memory, memory

In-text Question 4: Is the instruction mov 7h,eax valid in assembly language?


Answer: The move is invalid. This is because an immediate value cannot be a destination
operand.

2.6 Comments
Comments are important when we write programs. They explain the program’s
purpose, when was the program written and by whom. In large programs, comments
are also used in providing revision information in order to help understand some tricky
coding techniques within applications. There are two types of comment is 8086
assembly language programming namely: the single line and the multi-line comment.
The single line comment begin with a semicolon (;) while the multi-line comment
begin with the keyword COMMENT with a programmer-chosen character and ends
with the same programmer-chosen character

Example 10

Single line comment


mov eax,test ;mov register, memory

Multi-line comment
mov eax,test Comment * Assembly language is fun
I am enjoying it *

In-text Question 5: What character begins a single line comment in assembly language?
Answer: A semicolon (;) begins a single line comment in assembly language.

52
2.7 8086 Assembly Language Program Template
The template for writing assembly language program is given in Figure1.3.2.

TITLE Program Template


(Template.asm)
; Program Description:
; Author:
; Creation Date:
; Revisions:
; Date: Modified by:
INCLUDE Irvine32.inc

Figure 1.3.2: Assembly language template

The TITLE is an assembly language directive that is used to give a program name.
Statements proceeded by semicolon (;) are single line comments. The .data directive
begins the data segment. The .code directive begins the code segment. PROC
directive indicates the beginning of a procedure called main. The ENDP directive
end the procedure called main. END main directive terminates the program
successfully and return control to DOS

In-text Question 6: What is the function of the ENDP directive in assembly language?
Answer: The ENDP directive is used to end a procedure.

3.0 Tutor Marked Assignments (Individual or Group)


1. Show an example of a block comment in assembly language.
2. Explain the assembly language operand types with an example of each
operand type.
3. Differentiate between the TITLE and the .Data directive?

53
4.0 Conclusion/Summary
At the end of this session, we have studied the basics of assembly language
programming, which includes data type, variable declaration, arrays, operand types,
data transfer, comments and the 8086 assembly language program template. In the
next study session, you will be learning assembly language instructions, addressing
mode, jump and loop instruction.

5.0 Self-Assessment Questions and Answers


Questions
1. Give three advantages why you think the study of assembly language is
important?
2. What is a variable in assembly language?
3. What does the instruction var DB 10 DUP(?) mean in assembly language?
4. Is the instruction mov x,y valid in assembly language?

6.0 Answers to Self-Assessment Questions


1.
a. The knowledge of assembly language will improve our algorithmic
and coding skills.
b. Assembly language will introduce us to the knowledge of low-level
language.
c. We may need to use it to understand how hardware’s interact with
each other.

2. A variable in any program is a memory location that is given a name and


can be referenced during programming.
3. The instruction tells the assembler to create an array called var of type data
byte with 10 spaces and all initialised to zero.
4. The instruction is not valid. Assembly language does not permit memory to

54
memory data movement.

7.0 Additional Activities (Videos, Animations & Out of Class activities) e.g.
a. Visit U-tube add http://bit.ly/2UcFzF6 , http://bit.ly/2Zd252j ,
http://bit.ly/2Zd27XZ , http://bit.ly/2Z7szlR , http://bit.ly/2KFaweA ,
http://bit.ly/2H8BDg3. Watch the video & summarise in 1 paragraph
b. View the animation on add/site And critique it in the discussion forum
c. Take a walk and engage any 3 students on Basics of Assembly Language; In 2
paragraphs summarise their opinion of the discussed topic. Etc.

8.0 References/Further Readings


Irvine, Kip R., Assembly Language for x86 Processors, 7th Edition. Pearson,
2014. ISBN-13: 9780133769401 ISBN-10: 0133769402,
Hennessy, J. L, and Patterson, D. A., Computer Architecture: A Quantitative
Approach, 5th Edition. Morgan Kaufmann, 2011. ISBN-13 : 978-
0123838728 ISBN- 10 : 012383872X

STUDY SESSION 4
55
Arithmetical Instructions and Addressing Mode
Section and Subsection Headings:
Introduction
1.0 Learning Outcomes
2.0 Main Content
2.1-Assembly language Instructions
2.1.1-Add Instruction
2.1.2-Sub Instruction
2.1.3-mul Instruction
2.1.4 -Inc instruction
2.1.5-Dec instruction
2.2-Addressing Mode
2.2.1-Immediate Addressing Mode
2.2.2-Direct Addressing Mode
2.2.3-Register indirect Addressing Mode
2.2.4-Register Addressing Mode
2.2.5-Index Addressing Mode
2.2.6-Register Relative Addressing Mode
2.2.7-Base Plus Index Addressing Mode
2.2.8-Base Relative Plus Index Addressing Mode
2.3-JMP and LOOP Instruction
2.3.1-JMP
2.3.2-LOOP
3.0Tutor Marked Assignments (Individual or Group assignments)
4.0Study Session Summary and Conclusion
5.0Self-Assessment Questions and Answers
6.0Additional Activities (Videos, Animations & Out of Class activities)
7.0 References/Further Readings

56
Introduction:
You are welcome to this study session. In this session, I will be teaching you the
concepts of assembly language instructions, addressing mode, jump and loop
instruction.

1.0 Study Session Learning Outcomes


After studying this session, I expect you to be able to:
1. Use different assembly language instructions in a program
2. Use different directives during program development
3. Differentiate between the JMP and LOOP instructions

2.0 Main Content


2.1 Assembly Language Instructions
There are a number of instructions that form the driving force of an 8086 assembly
language. The most used instructions are the addition represented by the mnemonic
(ADD), the subtraction represented by the mnemonic (SUB), multiplication represent
by the mnemonic (MUL), the increment and decrement represented by the
mnemonic (INC) and (DEC) respectively.

2.1.1 Add Instruction


The ADD instruction performs addition between pairs of operands. For example
ADD AX, BX. This instruction adds the content of the second operand, which is BX
to the first operand, which is AX.

2.1.2 SUB Instruction


The SUB instruction performs subtraction between two pairs of operands. For
example SUB AX, BX. This instruction subtracts the content of the second operand
from the content of the first operand.

57
2.1.3 MUL Instruction
The MUL instruction is used for multiplication. The syntax for MUL is given below:
MUL register or memory location
Both the registers and memory locations can be either 8, 16 or 32 bits.

Example 1
MOV al, 2h
MOV bl, 5h
Mul bl ; this will multiply bl with whatever value is in al. The value of al here been
2h.

2.1.4 INC Instruction


The INC instruction increases the value of a register or memory location by 1. For
example, INC AX. This increases the content of AX by 1.

2.1.5 DEC instruction


The DEC instruction decreases the value of a register or memory location by 1. For
example, DEC AX. This decreases the content of AX by 1.

Example 2
Write a complete 8086 assembly language program that adds two 32 bits positive
numbers.

Solution
TITLE Add and Subtract (AddSub.asm)
; This program adds and subtracts 32-bit integers.
Include C:\Irvine\Irvine32.inc
Include; C:\Irvine\Irvine32.lib
Includelib C:\Irvine\Kernel32.Lib
includelib C:\Irvine\User32.Lib.code
Main PROC
mov eax, 10000h ; EAX = 10000h

58
Add eax, 40000h ; EAX = 50000h
Sub eax, 20000h ; EAX = 30000h
Call Dump Regs ; display registers
Exit
Main ENDP
END main
In-text Question 1: What is the use of the DEC instruction in assembly language?
Answer: The DEC instruction decreases the value of a register or memory location by 1. For
example, DEC AX. This decreases the content of AX by 1.

2.2Addressing Mode
Addressing modes helps us understand the different types of operands and the way
the operands are accessed during instruction execution. There are eight different
types of addressing modes in 8086 architectures namely: immediate addressing
mode, direct addressing mode, and register addressing mode, register indirect
addressing mode, index addressing mode, register relative addressing mode, base
plus index addressing mode and base relative plus index addressing mode.

2.2.1 Immediate Addressing Mode


Immediate addressing mode is a type of addressing mode in which an immediate
data is embedded as part of an instruction and appears in the form of successive byte
or bytes. An example of immediate addressing mode is:
mov ax,10AB

2.2.2 Direct Addressing Mode


Direct addressing mode is a type of addressing mode in which a 16-bit memory
address is directly in an instruction as part of the instruction. An example of a direct
addressing mode is:
mov ax,[5000H]

59
2.2.3 Register Addressing Mode
Register addressing mode is a type of addressing mode in which data is saved into a
register, which is 8, 16 or 32-bit register. Note that all the register inside the CPU can
be used for indirect addressing except the instruction pointer (IP). An example of a
register direct addressing is:
mov al,bl
mov ax,bx

2.2.4 Register indirect Addressing Mode


Register indirect addressing is a type of addressing mode in which the address of a
memory location that contains data or operand is indirectly determined using the
offset register. An example of register indirect addressing is:
mov ax,[bx]

2.2.5 Index Addressing Mode


Index addressing mode is a type of addressing mode in which the offset of an
operand is stored in one of the index registers. Note that the data segment register
(DS) is the default segment for index register SI and DI. An example of index
addressing is:
mov ax,[si]

2.2.6 Register Relative Addressing Mode


Register relative addressing mode is a type of addressing mode in which stored data
is only available in an effective address that is obtained by adding an 8,16 or 32 bit
displacement with the content of any one of the registers bx, bp, si and di in the
default segment which can either be (DS or ES). An example of register relative
addressing is:
mov ax,50H[bx]

60
2.2.7 Base plus Index Addressing Mode
Base plus index addressing mode is a type of addressing mode in which a stored data
is available in an effective address that is obtained by adding the content of a base
register and the content of an index register. An example of the base plus index
addressing is:
mov ax,[bx][si]

2.2.8 Base Relative plus Index Addressing Mode


The base relative plus index addressing is a type of addressing mode in which a
stored data is located in an effective address that is obtained by adding an 8 or 16 bit
displacement with the sum of contents of any one of the base register and any one of
the index registers in a default segment. An example of a base relative plus index
addressing is:
mov ax,50H[bx][si]

In-text Question 2: Consider the instruction below and determine which addressing mode the
instruction belongs?
mov ax,[bx]
Answer: Index addressing mode

2.3 - JMP and LOOP Instruction


2.3.1 - JMP
The jump instruction in 8086 assembly language program is divided in to two
namely: the conditional and the unconditional jump as shown in Figure1.4.1:

JUMP

Unconditional Conditional

Figure1.4.1: Classification of the JUMP instruction

61
The unconditional jump has one instruction which is the JMP. The JMP is used to
transfer control in a program to any memory location by specifying a 16-bit
memory address, which will serve as the operand for the JMP. JMP is able to
transfer control both forward and backward. It can jump anywhere in current code
segment (65,535 bytes). The syntax for the JMP is:
JMP label
To declare a label in a program, we just type its name and add ":" to the end. A
label can be any character combination but it cannot start with a number, for
example, here are 3 legal label definitions:
label1:
label2:
a:
Label can be declared on a separate line or before any other instruction, for
example:
X1:
MOV AX, 1
or
x2: MOV AX, 2

Example 3
Write a program to sum two numbers in a register using the JMP instruction.
Solution

include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib
includelib C:\Irvine\Kernel32.Lib
includelib C:\Irvine\User32.Lib.code
main PROC
mov ax, 5 ; set ax to 5.
mov bx, 2 ; set bx to 2.
jmp calc ; go to 'calc'.
Back: jmp stop ; go to 'stop'.
calc:
Add ax, bx ; add bx to ax.

62
jmp back ; go 'back'.
stop:
ret
main ENDP
END main

There are several ways to calculate the sum of two numbers, this is just one just
one example that uses the JMP instruction.
The conditional jump has different instructions that will operate under certain
conditions of a flag bit. Some of these jump conditions includes the JC (jump if
carry), JNC (jump if no carry), JZ (jump if zero), JNZ (Jump if not zero). A more
detail list of conditional jumps and the flags they affect is presented in Table1.4.1:
Table 1.4.1: Conditional Jump

Instructio

n Description Condition Opposite Instruction

JZ , JE Jump if Zero (Equal). ZF = 1 JNZ, JNE

JC , JB, Jump if Carry (Below,

JNAE Not Above Equal). CF = 1 JNC, JNB, JAE

JS Jump if Sign. SF = 1 JNS

JO Jump if Overflow. OF = 1 JNO

JPE, JP Jump if Parity Even. PF = 1 JPO

Jump if Not Zero (Not

JNZ , JNE Equal). ZF = 0 JZ, JE

JNC , JNB, Jump if Not Carry (Not

JAE Below, Above Equal). CF = 0 JC, JB, JNAE

JNS Jump if Not Sign. SF = 0 JS

63
JNO Jump if Not Overflow. OF = 0 JO

Jump if Parity Odd (No

JPO, JNP Parity). PF = 0 JPE, JP

2.3.2 Loop

The loop instruction is the combination of the decrement CX or ECX register and
JNZ conditional jump which means jump if not zero. In 8086 microprocessors, the
LOOP instruction decrements the value in CX or ECX registers and then checks the
new value in CX or ECX register. If the new value in the CX or ECX register is not
equal to zero, it jumps to an address label indicated in the loop instruction.
Otherwise, if the value in the CX or ECX register equals to zero, the next sequential
instruction executes.

Example 4
Write an assembly program using the LOOP instruction that calculates the sum of
5+4+3+2+1.

Solution

include C:\Irvine\Irvine32.inc

includelib C:\Irvine\Irvine32.lib

includelib C:\Irvine\Kernel32.Lib

includelib C:\Irvine\User32.Lib

.code

main PROC

mov ax,0

64
mov ecx,5

L1: add ax,cx

Loop L1

call Clrscr

call DumpRegs

exit

main ENDP

END main

In-text Question 3: JMP is a conditional transfer instruction? True or False


Answer: False

3.0 Tutor Marked Assignments (Individual or Group)


1. Why is it good to understand the concept of addressing mode?
2. Differentiate between direct addressing and register addressing modes?
3. Explain the difference between the two types of jump instructions in assembly
language?

4.0 Conclusion/Summary
At the end of this session, we have studied various assembly language instructions,
addressing mode, jump and loop instruction. In the next study session, you will be
learning data related operatives such as Offset Operator, PTR Operator, Type
Operator, Length of Operator, and Size Of Operator in assembly language. We will
also be studying different assembly language Directive.

65
5.0 Self-Assessment Questions
Questions
1. How many address instruction is in IMUL C?
2. Which addressing mode is used for the initialisation of the variable?
3. The instruction MOV AX , 300 is an example of which addressing mode?
4. Write a simple assembly language code for the implementation of AX =
(-val2+BX)-val4

6.0 Answers to Self-Assessment Questions


1. One
2. Immediate addressing
3. Immediate addressing
4. mov ax, val2
Neg ax
Add ax, bx
Sub ax, val4

7.0 Additional Activities (Videos, Animations & Out of Class activities) e.g.
a. Visit U-tube add http://bit.ly/2UcFzF6 , http://bit.ly/2z40j4X ,
http://bit.ly/2KH5fTQ , http://bit.ly/2Z9NeRZ , http://bit.ly/2Nf0VwM ,
http://bit.ly/2PcVgds. Watch the video & summarise in 1 paragraph
b. View the animation on add/site and critique it in the discussion forum
c. Take a walk and engage any 3 students on Arithmetical Instruction and
Addressing Mode; In 2 paragraphs summarise their opinion of the discussed topic.
etc.

66
8.0 References/Further Readings
Irvine, Kip R., Assembly Language for x86 Processors, 7th Edition. Pearson,
2014. ISBN-13: 9780133769401 ISBN-10: 0133769402,
Hennessy, J. L, and Patterson, D. A., Computer Architecture: A Quantitative
Approach, 5th Edition. Morgan Kaufmann, 2011. ISBN-13 : 978-
0123838728 ISBN- 10 : 012383872X

67
MODULE 2
Contents:
Study Session 1: Data-Related Operators and Directives
Study Session 2: Interrupts and Stack Operations
Study Session 3: Program Design Using Procedures
Study Session 4: Flowchart

STUDY SESSION 1
Data-Related Operators and Directives
Section and Subsection Headings:
Introduction
1.0 Learning Outcomes
2.0 Main Content
2.1- Data Related Operators
2.1.1-Offset Operator
2.1.2-PTR Operator
2.1.3-Type Operator
2.1.4 –Length Of Operator
2.1.5-SizeOf Operator– Label Directive
2.2-Directive
2.2.1-ASSUME Directive
2.2.2 - LABEL Directive
3.0 Tutor Marked Assignments (Individual or Group assignments)
4.0 Study Session Summary and Conclusion
5.0 Self-Assessment Questions and Answers
6.0 Additional Activities (Videos, Animations & out of Class activities)
7.0 References/Further Readings

68
Introduction:
You are welcome to this study session which is titled data-related operators and
directives. In this study session, I will be discussing on data related operatives such
as Offset Operator, PTR Operator, Type Operator, Length Of Operator, and Size Of
Operator in assembly language. I will also introduce you to different assembly
language Directive.

1.0 Study Session Learning Outcomes


After studying this session, I expect you to be able to:
1. Use different data related operators when developing assembly language program
2. Use different type of directives when developing assembly language program

2.0 Main Content


2.1 Data Related Operators
Data related operators are executable statements in assembly language that are used
to get address of all size inputs. These operators include the Offset Operator, PTR
Operator, Type Operator, Length of Operator, and Size of Operator.

2.1.1 Offset Operator


The OFFSET operator returns the distance in bytes, of a label from the beginning of
its enclosing segment as shown in Figure2.1.1. The protected mode addressing uses
32 bits and the real mode addressing uses the16 bits.

offset

data segment:

myByte

Figure2.1.1: Offset

69
Example 1
Let us assume that a data segment begins at 00404000h:
Thus

data
bVal BYTE ?
wVal WORD ?
dVal DWORD ?
dVal2 DWORD ?
.code
mov esi,OFFSET bVal ; ESI = 00404000
mov esi,OFFSET wVal ; ESI = 00404001
mov esi,OFFSET dVal ; ESI = 00404003
mov esi,OFFSET dVal2 ; ESI = 00404007

2.1.2 PTR Operator


The PTR operator overrides the default type of a label (variable). It provides a
programme with the flexibility to access part of a variable.

Example 2
Consider the program below:

include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib
includelib C:\Irvine\Kernel32.Lib
includelib C:\Irvine\User32.Lib
.date
test dw 12345678h
.code
main PROC
mov ax,test ; error, worddword
mov ax,word PTR test ; return 5678h
main ENDP
END main

70
The mov ax,test will return an error because the operands are not of the same size.
However, the second line will not return an error message because it gets a word size
portion from the test variable and save it to ax. In this case, 5678h is returned and
save to ax. This is because of the little endian order storage mechanism.

Little Endian Order


This is one type of technique that is used for storing data into the RAM. As an
example, consider an integer data as 0x01234567. The computer RAM is divided
into blocks and each block has an address as shown in Figure2.1.2:

1 byte memory

67 45 23 01
0x00 0x20 0x21 0x22 0x23 High
Low
Figure 2.1.2: little endian order

The little endian computer store data in RAM from high to low. That means the
storage goes from right to left. However, when the numbers are loaded from memory
into registers, the bytes are automatically re-reversed into their correct positions. It is
good to note the PTR is useful for accessing part of this memory location as shown
in the example 2.

2.1.3 Type Operator


The TYPE operator returns the size, in bytes, of a single element of a data
declaration. For example, its returns one for byte, two for word, four for double word
and eight for quad word etc.
Example 3
Include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib

71
includelib C:\Irvine\Kernel32.Lib
includelib C:\Irvine\User32.Lib

main PROC
.data
var1 BYTE ?
var2 WORD ?
var3 DWORD ?
Var4 QWORD?
.code
mov eax, TYPE var1 ;1
mov eax, TYPE var2 ;2
mov eax,TYPE var3 ;4
mov eax,TYPE var4 ;8
call DumpRegs ; display registers
exit
main ENDP
END main

2.1.4 Length Of Operator


The LENGTHOF operator counts the number of elements in a single data declaration
as shown in the example 4.
Example 4:
include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib
includelib C:\Irvine\Kernel32.Lib
includelib C:\Irvine\User32.Lib

main PROC
.data LENGTHOF
byte1 BYTE 10,20,30 ; 3
array1 WORD 30 DUP(?),0,0 ; 32
array2 WORD 5 DUP(3 DUP(?)) ; 15
array3 DWORD 1,2,3,4 ; 4
digitStr BYTE "12345678",0 ; 9
.code
mov ecx,LENGTHOF array1 ; 32
call DumpRegs ; display registers
exit
Main ENDP
END main
72
A data declaration spans multiple lines if each line (except the last) ends with a
comma. The LENGTHOF and SIZEOF operators include all lines belonging to the
declaration.

Example 5

include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib
includelib C:\Irvine\Kernel32.Lib
includelib C:\Irvine\User32.Lib

main PROC

.data
array WORD 10,20,
30,40,
50,60
.code
mov eax, LENGTHOF array ;6
call DumpRegs ; display registers
exit
main ENDP
END main

In the following example 6, array identifies only the first WORD declaration because
it does not span over multiple lines like in example 5.

Example 6

Include C:\Irvine\Irvine32.inc
Includelib C:\Irvine\Irvine32.lib
includelib C:\Irvine\Kernel32.Lib
Includelib C:\Irvine\User32.Lib

Main PROC
.data
Array WORD 10, 20
WORD 30, 40

73
WORD 50, 60
.code
mov eax,LENGTHOF array ;2
call DumpRegs ; display registers
exit
main ENDP
END main

2.1.5 Size Of Operator


The SIZEOF operator returns a value that is equivalent to multiplying
LENGTHOF by TYPE.

Example 7

include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib
includelib C:\Irvine\Kernel32.Lib
includelib C:\Irvine\User32.Lib

main PROC
.data SIZEOF
Byte1 BYTE 10, 20,30 ; 3
array1 WORD 30 DUP(?),0,0 ; 64
array2 WORD 5 DUP(3 DUP(?)) ; 30
array3 DWORD 1,2,3,4 ; 16
digitStr BYTE "12345678",0 ; 9

.code
mov ecx,SIZEOF array1 ; 64
call DumpRegs ; display registers
exit
main ENDP
END main

In-text Question 1: The LENGTHOF operator counts the number of elements in a single data
declaration? True or False
Answer: True

74
2.2 Assembler Directive
This special code is placed in an assembly language program to instruct the
assembler to perform a particular task of function. The assembler directives can be
used to define symbol values, reserve and initialize storage space for variables and
control the placement of program code. There are different types of directives in
assembly language, some of which we have been using in our initial program.
Examples are the DB, DW, DD, DQ and DT which we have been using for data
definition. Other type of directive are the ASSUME, the LABEL etc.

2.2.1 ASSUME Directive


The ASSUME directive is used to tell the assembler that the name of a logical
segment should be used for specified segment. 8086 works directly with four
physical segments which are the data segment, code segment, stack segment and
the extra segment. The syntax of the ASSUME directive is shown in example 8
and 9.

Example 8
ASSUME CS:CODE ; This reads ASSUME CS as CODE

This tells the assembler that the logical segment named code contains the
instruction statement for the program and should be treated as CODE segment.

Example 9

ASSUME DS:DATA ; this reads ASSUME DS as DATA

This tells the assembler that for any instruction which refers to a data in data
segment, data will be found in logical segment DATA

75
2.2.2 LABEL Directive
The label directive assigns an alternate label name and type to an existing storage
location. It does not allocate any storage of its own. However using the LABEL
directive remove the need for the PTR operator in a program.

In-text Question 2: What is a Directive in assembly language?


Answer: A directive is a special code that is placed in an assembly language program to instruct
the assembler to perform a particular task of function.

3.0 Tutor Marked Assignments (Individual or Group)


1. What are data related operators in assembly language?
2. Explain in detail what you understand by an assembler directive?
3. What is the function of a LABEL directive in assembly language?

4.0 Conclusion/Summary
At the end of this session, we have studied data related operatives such as Offset
Operator, PTR Operator, Type Operator, Length Of Operator, and size Of Operator
in assembly language. We have also studied different assembly language Directive.
In the next study session, you will be learning assembly language interrupts and
stack operations.

6.0 Self-Assessment Questions


Question
Consider the below data definition and answer the questions that follows:
.data byte1 BYTE 10,20,30
array1 WORD 30 DUP(?),0,0
array2 WORD 5 DUP(3 DUP(?))
array3 DWORD 1,2,3,4
digitStr BYTE "12345678",0
1. What is the Type Of array1
76
2. What is the lenthOf array2
3. What is the sizeOf array1
4. What is the lenthOf digitStr

6.0 Answers to Self-Assessment Questions


1. 1

2. 15

3. 3

4. 9

7.0 Additional Activities (Videos, Animations & Out of Class activities) e.g.
Visit U-tube add http://bit.ly/2UcFzF6 , http://bit.ly/2PdfRxU ,
http://bit.ly/2Ng7sHq , http://bit.ly/31QCKsO. Watch the video & summarise in 1
paragraph
View the animation on add/site and critique it in the discussion forum
Take a walk and engage any 3 students on Data-Related Operators and Directives;
In 2 paragraphs summarise their opinion of the discussed topic. etc.

8.0 References/Further Readings


Irvine, Kip R., Assembly Language for x86 Processors, 7th Edition. Pearson,
2014. ISBN-13: 9780133769401 ISBN-10: 0133769402,
Hennessy, J. L, and Patterson, D. A., Computer Architecture: A Quantitative
Approach, 5th Edition. Morgan Kaufmann, 2011. ISBN-13 : 978-
0123838728 ISBN- 10 : 012383872X

77
STUDY SESSION 2
Interrupts and Stack Operations
Section and Subsection Headings:
Introduction
1.0 - Learning Outcomes
2.0 - Main Content
2.1-Interrupts
2.2- Stack
3.0 -Tutor Marked Assignments (Individual or Group assignments)
4.0 -Study Session Summary and Conclusion
5.0 -Self-Assessment Questions and Answers
6.0 -Additional Activities (Videos, Animations & Out of Class activities)
7.0 - References/Further Readings

Introduction:
You are welcome to this study session titled Interrupts and Stack Operations. In
this study, I will take you through the mechanisms of assembly language interrupt
and stack operations.

1.0 Study Session Learning Outcomes


After studying this session, I expect you to be able to:
1. explain the mechanism behind Interrupts.
2. explain the mechanism behind stack operations.

78
2.0 Main Content
2.1 Interrupts
An interrupt is a method of creating a temporary halt during program execution in
order to allow peripheral devices to access the microprocessor. A microprocessor
respond to that interrupt with an interrupt service routine. An interrupt service
routine is a short program to instruct the microprocessor on how to handle an
interrupt. Interrupt are useful when interfacing I/O devices with low data transfer
rate like a keyboard or a mouse in which case controlling the device processing
time. For example, consider a program running and an interrupt occur such as the
printer interrupt. The microprocessor will immediately create an interrupt a service
routine so that the interrupt will be serviced before the execution of the main
program continues. There are different kinds of interrupts that can be generated in
8086 microprocessor. These interrupts can be classified into hardware or software
interrupts. Hardware interrupts are caused mainly by peripheral devices. The
hardware interrupt can further be divided into maskable and non-maskable
interrupt. The software interrupt is divided into 256 types of interrupts. Figure
2.2.1 shows the different classification of interrupts.

Interrupt

Hardware Software

256 types of
Maskable software
Non-maskable
interrupt

Figure2.2.1: Classification of interrupts

79
The maskable interrupts are those kind of interrupts that microprocessor can ignore
when it is running a program so that it can be serviced when the running program
finishes execution. However, the non-maskable interrupt is that which cannot be
ignored by the microprocessor, thus, a running program will have to be paused so
that the microprocessor serviced the interrupts before program execution
continues.

In-text Question 1: What is an interrupt?


Answer: An interrupt is a method of creating a temporary halt during a program execution in
order to allow peripheral devices to access the microprocessor.

2.2 Stack
Stack is a linear data structure which follows a particular order in which the
operations are performed. The order may be LIFO (Last In First Out) or
FILO(First In Last Out). A stack in CPU is a combination of an addressable
memory and a register called a stack pointer (SP). The stack pointer contains an
address to a cell in memory which is called the top of the stack. This is shown in
Figure 2.2.2

Memory

Stack pointer (SP)

Figure2.2.2: Stack

There are two basic operations that are performed in the stack namely the PUSH

which adds an item in the stack and the Pop which removes an item from the stack.

The items are popped in the reversed order in which they are pushed. An example

is shown in Figure 2.2.3 and 2.2.4 respectively.

80
Example 1

A 32 bit PUSH

BEFORE AFTER

00001000 00000006 ESP 00001000 00000006

00000FFC 00000FFC 000000A5 ESP

00000FF8 00000FF8

00000FF4 00000FF4

00000FF0 00000FF0

Figure2.2.3:A 32 bit PUSH

A POP

BEFORE AFTER

00001000 00000006 00001000 00000006

00000FFC 000000A5 00000FFC 000000A5

00000FF8 00000001 00000FF8 00000001 ESP


00000FF4 00000002 ESP 00000FF4

00000FF0 00000FF0

Figure2.2.4: A POP

In-text Question 2: What are the two basic stack operations?


Answer: There are two basic operations are performed in the stack namely the PUSH
which adds an item in the stack and the Pop which removes an item from the stack.

81
3.0 Tutor Marked Assignments (Individual or Group)

1. Briefly explain how a microprocessor responds to an interrupt request.

2. Differentiate between maskable and non-maskable interrupt.


3. What is a stack data structure?

4.0 Conclusion/Summary
At the end of this session, we have studied the mechanism of interrupt and stack
operations in assembly language. In the next study session, you will be learning
program design using procedures, which involves the definition of a procedure, the
advantages and disadvantages of using procedures, the template for creating
procedures. You will also learn how to call and return from a procedure, labels in
procedures and nested procedures.

5.0 Self-Assessment Questions


Questions
1. What is maskable interrupt?
2. What is an interrupt service routine?
3. What is a stack?
4. What are the two basic operation of the stack?

6.0 Answers to Self-Assessment Questions


1. Maskable interrupts are those kind of interrupt that microprocessor can
ignore when it is running a program so that it can be serviced when the
running program finishes execution.
2. An interrupt service routine is a short program to instruct the microprocessor
how to handle an interrupt.
3. Stack is a linear data structure, which follows a particular order in which the
operations are performed. The order may be LIFO (Last In First Out) or

82
FILO (First In Last Out).
4. There are two basic operations are performed in the stack namely the PUSH
which adds an item in the stack and the Pop which removes an item from the
stack.

7.0 Additional Activities (Videos, Animations & Out of Class activities) e.g.
a. Visit U-tube add http://bit.ly/2zdnIAJ , http://bit.ly/2KFQCQx ,
http://bit.ly/2Hea19k , http://bit.ly/2UcFzF6 , http://bit.ly/2NczkfA. Watch the
video & summarise in 1 paragraph
b. View the animation on add/site and critique it in the discussion forum
c. Take a walk and engage any 3 students on Interrupts and Stack Operations; In 2
paragraphs summarise their opinion of the discussed topic. etc.

8.0 References/Further Readings


Irvine, Kip R., Assembly Language for x86 Processors, 7th Edition. Pearson,
2014. ISBN-13: 9780133769401 ISBN-10: 0133769402,
Hennessy, J. L, and Patterson, D. A., Computer Architecture: A Quantitative
Approach, 5th Edition. Morgan Kaufmann, 2011. ISBN-13 : 978-
0123838728 ISBN- 10 : 012383872X

83
STUDY SESSION 3
Program Design Using Procedures
Section and Subsection Headings:
Introduction
1.0 - Learning Outcomes
2.0 - Main Content
2.1 - Definition of a procedure
2.2 - Advantages of using procedures
2.3 - Disadvantage of using procedures
2.4 - Format of a procedure
2.5 - Calling and returning from a procedure
2.6 - Labels in procedures
2.7 - Nested Procedures
3.0 - Tutor Marked Assignments (Individual or Group assignments)
4.0 - Study Session Summary and Conclusion
5.0 - Self-Assessment Questions and Answers
6.0 - Additional Activities (Videos, Animations & Out of Class activities)
7.0 - 9.0 - References/Further Readings

Introduction:
You are welcome to this study session titled program design using procedures. In
this session, I will be introducing you on how to write programs using procedures.
Thus, we will learn what an assembly language procedure is, the advantages and
disadvantages of using procedures, the template for creating procedures. We will also
learn how to call and return from a procedure, labels in procedures and nested
procedures.

84
1.0 Study Session Learning Outcomes
After studying this session, I expect you to be able to:
1. Define a procedure
2. Use simple procedures during assembly language program development
3. Use nested procedures during assembly language program development

2.0 - Main Content


2.1 - Definition of a procedure
A procedure is a group of instruction that perform one task out of a main task. It is a
reusable section of a code that is written once but can be used many times within a
program.

In-text Question 1: What is procedure?


Answer: A procedure is a group of instruction that perform one task out a main task. It is a
reusable section of a code that is written once but can be used many times within a program

2.2 - Advantages of Using Procedures


A procedure has several advantages which include:
1. The improvement of code readability. This is because with procedures,
program codes need not to be laid out as one long sequence.
2. Improve memory utilisation. This is because it is only written once but used
a number of times.
3. Allows code reusability. This is because a procedure can be written once
and called from more than one place in the code.
4. Allows tasks to be broken down into simpler components. This is because
procedures can be written for certain tasks (procedures can also call other
procedures).
5. Modular code facilitates modification.

85
In-text Question 2: List three advantages of using procedures in a program?
Answer: A procedure has several advantages, which include:
Code readability. This is because with procedures, program codes need not to be laid out
as one long sequence.
Memory utilization. This is because it is only written once but used a number of times.
Code reusability. This is because a procedure can be written once and called from more
than one place in the code.

2.3 - Disadvantage of Using Procedures


The only disadvantage of using procedures is that it take more time to link to a
procedure and return from the procedure.

In-text Question 3: What is the disadvantage of using procedures in a program?


Answer: The only disadvantage of using procedures is that it take more time to link to a procedure
and return from the procedure.

2.4 - Format of a Procedure


A procedure is always enclosed within some code segment. A procedure is defined
as:

PROCEDURE_NAME PROC
.
. The procedure goes here
.
PROCEDURE_NAME ENDP
ret
Where PROCEDURE_NAME is any valid identifier. PROC and ENDP are
assembly language directives.

2.5- Calling and Returning From A Procedure


There are two instructions that are associated with assembly language procedures.
The CALL instruction and the RET (return) instruction. A procedure is invoked by a
CALL instruction. A procedure call has the format:
CALL PROCEDURE_NAME
The RET instruction returns control to the caller of a procedure. There formats for
the RET instruction:

86
RET
A procedure may have zero, one, or more RET instructions. A procedure will have
no RET instruction in those programming situations where we do not want to
return control to the caller.

2.6 - Labels in Procedures


A label is an identifier that acts like a place marker for instructions and data. A label
that is placed just before an instruction implies the instruction’s address. A label that
is placed just before a variable implies the variables address. There are two parts to a
label namely: the data label and the code label. The data label identifies the location
of a variable thereby providing a convenient way to reference the variable in a code.
The assembler assigns a numeric address to each label. Example 1 shows the use of a
data label.

Example
Count DW 100

The code label is label area of a program where instructions are located. There are
two types of code labels: The local and the global code label. The global code label is
visible everywhere within a program and ends with a double colon (::) while the
local code label is only visible to statements inside the same procedure and ends with
a colon (:). Code labels are used as targets of a jumping and looping instruction.
Example 2 shows the use of a global and local label.

Example 2
A global label
main PROC
jmp target ; error
quit:: ; global label
exit
main ENDP
sub2 PROC

87
target: ; local label
jmp quit ; ok
ret
sub2 ENDP

A local label
target:
mov ax,bx
jmp target

2.7 - Nested Procedures


A nested procedure occurs when a first procedure calls another procedure before the
next procedure returns. Example 3 shows an example of a nested procedure.

Example 2

include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib
includelib C:\Irvine\Kernel32.Lib
includelib C:\Irvine\User32.Lib

.data

.code
main PROC
call sub1
mov ax,1
main ENDP
sub1 PROC
call sub2
ret
sub1 ENDP
sub2 PROC
ret
sub2 ENDP
END main

In example 2, we have three procedures namely the main, sub1 and sub2. The sub1
88
procedure is called by the main procedure. The sub1 procedure also calls another
procedure called sub2 which has the ret instruction to resume control to the previous
calling program right after the call instruction.

In-text Question 4: What is a nested procedure?


Answer: A nested procedure occurs when a first procedure calls another procedure before the next
procedure returns.

3.0 Tutor Marked Assignments (Individual or Group)


1. Give three reasons why the use of procedures is important during program
writing.
2. What instruction is used to invoke a procedure in assembly language?
3. Differentiate between a code label and a data label in assembly language

4.0 Conclusion/Summary
At the end of this session, we have studied program design using procedures. Thus,
we have learnt what an assembly language procedure is, the advantages and
disadvantages of using procedures, the template for creating procedures. We have
also learnt how to call and return from a procedure, labels in procedures and nested
procedures. In the next study session, you will be learning algorithm representation
using flowchart.

5.0 Self-Assessment Questions


Questions
1. The return address of a procedure is pointed by?
2. What is a nested procedure?
3. What is a Label in assembly language?
4. List the two types of labels in assembly language.

89
6.0 Answers to Self-Assessment Questions
1. Program counter
2. A nested procedure involves having one procedure call another procedure.
3. A label is an identifier that acts like a place marker for instructions and data.
4. Local and global label.

7.0 Additional Activities (Videos, Animations & Out of Class activities) e.g.
a. Visit U-tube add http://bit.ly/2UcFzF6 , http://bit.ly/2MosQec ,
http://bit.ly/2Mqfgqu , http://bit.ly/31NTa4U , http://bit.ly/2z6nnzN. Watch the
video & summarise in 1 paragraph
b. View the animation on add/site and critique it in the discussion forum
c. Take a walk and engage any 3 students on Program Design using Procedures; In
2 paragraphs summarise their opinion of the discussed topic. etc.

8.0 References/Further Readings


Irvine, Kip R., Assembly Language for x86 Processors, 7th Edition. Pearson,
2014. ISBN-13: 9780133769401 ISBN-10: 0133769402,
Hennessy, J. L, and Patterson, D. A., Computer Architecture: A Quantitative
Approach, 5th Edition. Morgan Kaufmann, 2011. ISBN-13 : 978-
0123838728 ISBN- 10 : 012383872X

90
STUDY SESSION 4
Flowchart
Section and Subsection Headings:
Introduction
1.0 - Learning Outcomes
2.0 - Main Content
2.1-Definition of a Flowchart
2.2-Uses of a Flowchart
2.3-Symbols of a flowchart
2.4-Examples
3.0 - Tutor Marked Assignments (Individual or Group assignments)
4.0 - Study Session Summary and Conclusion
5.0 - Self-Assessment Questions and Answers
6.0 - Additional Activities (Videos, Animations & Out of Class activities)
7.0 - References/Further Readings

Introduction:
You are welcome to this study session titled flowcharts. In this session, I will
introduce you on how to represent an algorithm using a flowchart.

1.0 Study Session Learning Outcomes


After studying this session, I expect you to be able to:
1. Identify the different symbols that are used for flowchart design
2. Use the different symbols for flowchart to graphically represent algorithms.

91
2.0 Main Content
2.1 Definition of a Flowchart
A flowchart is graphical representation of any algorithm or process. An algorithm
here refers to the sequence of steps that need to be followed in order to solve a
particular problem.

In-text Question 1: What is a flowchart?


Answer: A flowchart is graphical representation of any algorithm. An algorithm here refers to the
sequence of steps that need to be followed in order to solve a particular problem.

2.2 Uses of a Flowchart


Some of the common uses of flowcharts include:
i. Planning a new project
ii. Documenting a process
iii. Modelling a business process
iv. Managing workflow
v. Auditing a process
vi. Mapping computer algorithms
vii. Data management
viii. Chemical and process engineering

2.3 Symbols of a Flowchart


A flowchart is made up of a number of symbols and each symbol represents a given
process. Example of some these symbols are shown in Figure 2.4.1.

92
Start/Stop Symbol

Input/Output Symbol

Process Symbol

Condition Symbol

Manual Input Symbol

Connector Symbol

Display Symbol

Figure2.4.1: Flowchart symbols

93
2.4 Examples
Figure 2.4.2 shows a flowchart that simply displays a name.

Start

Display Name

Stop

Figure 2.4.2: Flowchart for Displaying Name

Figure 2.4.3 is a flowchart that is used for displaying the sum of two numbers A
and B that are inputted by a user.

Start

Input A and B

C=A+B

Display C

Stop

Figure 2.4.3: Flowchart for Adding two numbers

94
Figure 2.3.4 shows a flowchart that takes two numbers A and B from a user,
compares the numbers and then displays the larger of the two numbers.

Start

Input A and B

Is A > B
Display “A is Yes No Display “B is
larger” larger”

Stop

Figure 2.4.4: Flowchart for displaying the larger of two numbers

3.0 Tutor Marked Assignments (Individual or Group)


1. What do you understand by an algorithm?
2. Highlight on five common uses of a flowchart.
3. Draw a flowchart that take two numbers A and B as input from the user,
compare the numbers and then display the smaller of the two numbers.

4.0 Conclusion/Summary
At the end of this session, we have studied algorithm representation using
flowchart. In the next study session, you will be learning CPU status flag and
Boolean comparison operations in assembly language.

95
5.0 Self-Assessment Questions
Questions
1. What is a flowchart?
2. Give three common uses of a flowchart.

6.0 Answers to Self-Assessment Questions


1. A flowchart is graphical representation of any algorithm or process.
2. Three common uses of flowcharts include:
i. Planning a new project
ii. Documenting a process
iii. Mapping computer algorithms

7.0 Additional Activities (Videos, Animations & Out of Class activities) e.g.
a. Visit U-tube add http://bit.ly/2UcFzF6 , http://bit.ly/2NheZG0 ,
http://bit.ly/2HaW9wj , http://bit.ly/2KQitwq , http://bit.ly/31P2mpW. Watch the
video & summarise in 1 paragraph
b. View the animation on add/site and critique it in the discussion forum
c. Take a walk and engage any 3 students on Flowchart; In 2 paragraphs
summarise their opinion of the discussed topic. etc.

8.0 References/Further Readings


Irvine, Kip R., Assembly Language for x86 Processors, 7th Edition. Pearson,
2014. ISBN-13: 9780133769401 ISBN-10: 0133769402,
Hennessy, J. L, and Patterson, D. A., Computer Architecture: A Quantitative
Approach, 5th Edition. Morgan Kaufmann, 2011. ISBN-13 : 978-
0123838728 ISBN- 10 : 012383872X

96
MODULE 3
Contents:
Study Session 1: Boolean and Comparison Instructions
Study Session 2: Conditional Jumps
Study Session 3: Conditional Loop Instructions
Study Session 4: Conditional Structures

STUDY SESSION 1
Boolean and Comparison Instructions
Section and Subsection Headings:
Introduction
1.0 - Learning Outcomes
2.0 - Main Content
2.1 - CPU Status Flags
2.2 - AND Instruction
2.3 - OR Instruction
2.4 - XOR Instruction
2.5 - NOT Instruction
2.6 - TEST Instruction
2.7 - CMP Instruction
3.0 - Tutor Marked Assignments (Individual or Group assignments)
4.0 - Study Session Summary and Conclusion
5.0 - Self-Assessment Questions and Answers
6.0 - Additional Activities (Videos, Animations & Out of Class activities)
7.0 - References/Further Readings

97
Introduction:
You are welcome once again, this study session titled Boolean and comparison
instructions. In this study session, I will introduce you to different functions of
CPU status flag and Boolean comparison operations in assembly language.

1.0 Study Session Learning Outcomes


After studying this session, I expect you to be able to:
1. Explain the function of the different CPU status flag
2. Use the Boolean operators during assembly language program development

2.0 Main Content


2.1 CPU Status Flags
We use the CPU status flags are flags to determine the state of the processor. They
are modified automatically by some operation in the CPU in order to determine the
type and result of that operation. Note that these flags cannot be accessed directly by
a user. Examples of the CPU status flag are the:
i. Zero Flag: This flag is set to 1 when the result of an operation equals zero.
ii. Carry Flag: This flag is set to 1 when an instruction generates a result that
does not fit into the destination operand.
iii. Sign Flag: This flag is set to 1 if the destination operand is negative, otherwise
it is 0.
iv. Overflow Flag: This flag is set to 1when an instruction generates an invalid
signed result.
v. Parity Flag: This flag is set to 1 when an instruction generates an even
number of 1 bit in the low byte of the destination operand.
vi. Auxiliary Carry Flag: This flag is set to 1 when an operation produces a
carry out from bit 3 to bit 4

98
In-text Question 1: What is the function of the CPU status flag?
Answer: The CPU status flags are flags that used to determine the state of the processor.

2.2 AND Instruction


This performs a Boolean bit AND operation between two pair of matching bits in
two operands and places the result in the destination operand. The syntax of the
AND operation is given by:

AND destination, source

Note that both the source and destination operands must be of the same size. The
different combination of the AND operands are given by:

AND register,register
AND register memory
AND register, immediate value
AND memory, register
AND memory, immediate value
Example 1

0 0 0 0 0 0 0 1
AND 0 0 0 0 0 1 0 1
0 0 0 0 0 0 0 1

Example 2

include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib
includelib C:\Irvine\Kernel32.Lib
includelib C:\Irvine\User32.Lib

.data

.code
main PROC
mov ah,00000001b
mov bh,00000101b

99
and ah,bh
call Clrscr
call DumpRegs ; display registers
exit
main ENDP
END main

In-text Question 2: What is the function of the AND instruction in assembly language?
Answer: The AND instruction performs a Boolean bit AND operation between two pair of
matching bits in two operands and places the result in the destination operand

2.3 OR Instruction
This performs a Boolean bit OR operation between two pair of matching bits in two
operands and places the result in the destination operand. The syntax of the OR
operation is given by:

OR destination, source

Note that both the source and destination operands must be of the same size. The
different combination of the OR operands are given by:

OR register, register
OR register, memory
OR register, immediate value
OR memory, register
OR memory, immediate value
Example 3

0 0 0 0 0 0 0 1
OR 0 0 0 0 0 1 0 1
0 0 0 0 0 1 0 1

Example 4
include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib
includelib C:\Irvine\Kernel32.Lib

100
includelib C:\Irvine\User32.Lib

.data

.code
main PROC
mov ah,00000001b
mov bh,00000101b
or ah,bh
call Clrscr
call DumpRegs ; display registers
exit
main ENDP
END main

In-text Question 3: What is the function of the OR instruction in assembly language?


Answer: The OR instruction performs a Boolean bit OR operation between two pair of
matching bits in two operands and places the result in the destination operand.

2.4 XOR Instruction


This performs a Boolean bit XOR operation between two pair of matching bits in
two operands and places the result in the destination operand. The syntax of the
XOR operation is given by:

XOR destination, source

Note that both the source and destination operands must be of the same size. The
different combination of the OR operands are given by:

XOR register, register


XOR register, memory
XOR register, immediate value
XOR memory, register
XOR memory, immediate value

Example 5

0 0 0 0 0 0 0 1
XOR 0 0 0 0 0 1 0 1

101
0 0 0 0 0 1 0 0

Example 6
include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib
includelib C:\Irvine\Kernel32.Lib
includelib C:\Irvine\User32.Lib

.data

.code
main PROC
mov ah,00000001b
mov bh,00000101b
xor ah,bh
call Clrscr
call DumpRegs ; display registers
Exit
Main ENDP
END main

In-text Question 4: What is the function of the XOR instruction in assembly language?
Answer: The XOR instruction performs a Boolean bit XOR operation between two pair of
matching bits in two operands and places the result in the destination operand

1.5 NOT Instruction


This inverts the bits in an operand. The syntax of the NOT operation is given by:

NOT destination

Example 7

NOT 0 0 0 0 1 1 1 1
1 1 1 1 0 0 0 0

Example 8
Include C:\Irvine\Irvine32.inc

102
Includelib C:\Irvine\Irvine32.lib
Includelib C:\Irvine\Kernel32.Lib
includelib C:\Irvine\User32.Lib

.data

.code
Main PROC
mov ah,01111110b
not ah,
call Clrscr
call DumpRegs ; display registers
exit
Main ENDP
END main

In-text Question 5: What is the function of the NOT instruction in assembly language?
Answer: The NOT inverts the bits in an operand.

2.6 TEST Instruction


The TEST instruction performs the same action as the AND instruction. However,
the TEST instruction does not affect the destination operand. Thus, no operand is
modified by the TEST instruction. However, it affects the zero flag. The TEST
instruction is used to test whether a bit a zero or a one.

Example 9

include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib
includelib C:\Irvine\Kernel32.Lib
includelib C:\Irvine\User32.Lib

.data

.code
main PROC
mov ah, 00000001b
Test ah, 00000001b
Call Clrscr

103
Call DumpRegs ; display registers
Exit
Main ENDP
END main

In example 9, the test instruction performs, operation between the content of ah


register, and 00000001b.The result will affect the zero flag. If the zero flag is one,
this means that the results of test are all one, which means the bits tested does not
have a pair of matching bits. If the zero flag is zero, means the bits tested does have a
pair of matching bits.

In-text Question 6: What operands do the TEST instruction in assembly language modifies?
Answer: The TEST instruction does not modify any operands.

2.7 CMP Instruction


The CMP (compare) instruction performs an implied subtraction of the source
operand from the destination operand. The CMP instruction neither affects the source
nor the destination operand. The syntax of the CMP instruction is given as:

CMP destination, source

The CMP instruction is only used with conditional jumps instructions. The CMP
combined with the conditional jump instruction behave like the IF statement in high
level language. The CMP instruction affects only the zero flag and the carry flag.
The table below shows how the ZF and CF are affected by the CMP instruction.

CMP Instruction ZF CF
Destination < Source 0 1
Destination > Source 0 0
Destination = Source 1 0

Example 10
include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib
104
includelib C:\Irvine\Kernel32.Lib
Includelib C:\Irvine\User32.Lib

.data

.code
main PROC
mov eax,500
move ebx, 500
cmp eax,abx
call Clrscr
call DumpRegs ; display registers
exit
Main ENDP
END main

In-text Question 7: What is the function of the CMP instruction in assembly language?
Answer: The CMP (compare) instruction performs an implied subtraction of the source
operand from the destination operand.

3.0 Tutor Marked Assignments (Individual or Group)


1. Differentiate between the functions of the zero and carry flags?
2. Differentiate between the AND and TEST instructions?
3. What is the function of the CMP instruction in assembly language?

4.0 Conclusion/Summary
At end of this session, we have studied the functions of CPU status flag and
Boolean comparison operations in assembly language. In the next study session,
you will be learning different types of jump Instructions in assembly language.

105
5.0 Self-Assessment Questions
Questions
1. What condition sets the zero flag?
2. What operands gets modified with the execution of an AND operation?
3. What operands get modified with the execution of an XOR operation?
4. What operands get modified with the execution of a TEST operation?

6.0 Answers to Self-Assessment Questions


1. The Zero Flag is set to 1 when the result of an operation equals zero.
2. The destination operand
3. The destination operand
4. No operand is modified by the TEST instruction.

7.0Additional Activities (Videos, Animations & Out of Class activities) e.g.


a. Visit U-tube add http://bit.ly/2UcFzF6 , http://bit.ly/2z8oX4h ,
http://bit.ly/2P46aCa , http://bit.ly/2THnBHk. Watch the video & summarise in 1
paragraph
b. View the animation on add/site and critique it in the discussion forum
c. Take a walk and engage any 3 students on Boolean and Comparison
Instructions; In 2 paragraphs summarise their opinion of the discussed topic. etc.

8.0 References/Further Readings


Irvine, Kip R., Assembly Language for x86 Processors, 7th Edition. Pearson,
2014. ISBN-13: 9780133769401 ISBN-10: 0133769402,
Hennessy, J. L, and Patterson, D. A., Computer Architecture: A Quantitative
Approach, 5th Edition. Morgan Kaufmann, 2011. ISBN-13 : 978-
0123838728 ISBN- 10 : 012383872X

106
STUDY SESSION 2
Conditional Jumps
Section and Subsection Headings:
Introduction
1.0 - Learning Outcomes
2.0 - Main Content
2.1-Jump Based On Flags
2.1.1-Jump If Carry (JC)
2.1.2-Jump If Not Carry(JNC)
2.1.3-Jump If Zero (JZ)
2.1.4-Jump If Not Zero (JNZ)
2.2-Jump Based On Equality
2.2.1-Jump If Equal (JE)
2.2.2-Jump If Not Equal (JNE)
2.2.3-Jump If CX Is Not Equal Zero (JCXZ)
2.3-Jump Based Of Unsigned Comparison
2.4 -Jump Based Of Signed Comparison
3.0 - Tutor Marked Assignments (Individual or Group assignments)
4.0 - Study Session Summary and Conclusion
5.0 - Self-Assessment Questions and Answers
6.0 - Additional Activities (Videos, Animations & Out of Class activities)
7.0 - References/Further Readings

Introduction:
You are welcome to this study session titled conditional jumps. In this session, I
will take you through the different types of jump Instructions and their functions in
assembly language.

107
1.0 Study Session Learning Outcomes
After studying this session, I expect you to be able to:
1. Describe the function of the different jump instructions in assembly language
2. Use the different jump instructions during assembly language program
development.

2.0 Main Content


2.1 Jump Based On Flags
Conditional jumps based on flags are jumps that will only be made if a certain flag
is set during program execution. The conditional jumps are usually used with the
comparison instruction (CMP). The CMP instructions in such a case compare the
values of the source and destination operand, thereby affecting some CPU status flag.
The conditional jump checks the result of these flags and jump to certain part of the
program if the flag is set. Some of the conditional instructions are the JC,JNC, JZ,
JNZ, JS, and JNS etc

In-text Question 1: What instruction is usually used with conditional jump instructions in
assembly language?
Answer: The carry flag

2.1.1 Jump If Carry (JC)


This type of jump checks to see whether the CF is set. If the CF flag is set, the jump
happens. Otherwise the jump will not occur. The CF is set if the result of a
comparison operation is not equal. Otherwise, it is cleared.

Example 1
Include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib
includelib C:\Irvine\Kernel32.Lib
includelib C:\Irvine\User32.Lib

.data

108
.code
Main PROC
mov ax,4
cmp ax,5
jc L2
mov bx,1
call Clrscr
call DumpRegs ; display registers
exit
L2:
mov bx,6
call Clrscr
call DumpRegs ; display registers
Exit
Main ENDP
END main

Note that in example 1, the value 4 is moved into ax register. The CMP operator
performs a non-destructive subtraction operation of its source operand from its
destination operand. This subtraction does not affect any of the two operands.
However, it only affects a CPU status flag. In this case, 4 compared with 5 is not
equal as such the CF is set to 1. This makes the JC condition true as such the CPU
jump to L2 and move 6 to register bx. However, if CF is not set, the next instruction
after the jump condition continues executing.

In-text Question 2: Which flag is affected by the JC instruction in assembly language?


Answer: The carry flag

2.1.2 Jump If Not Carry


This type of jump also checks to see whether the CF is set. If the CF flag is set, the
jump happens. Otherwise the jump will not occur. The CF is set if the result of a
comparison operation is not equal. Otherwise, it is cleared.

109
Example 2

include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib
includelib C:\Irvine\Kernel32.Lib
Includelib C:\Irvine\User32.Lib

.data

.code
Main PROC
Mov ax,5
cmp ax,5
jnc L2
mov bx,1
call Clrscr
call DumpRegs ; display registers
exit
L2:
mov bx,6
call Clrscr
call DumpRegs ; display registers
exit
main ENDP
END main

Note that in example 2, the value 5 is moved into ax register. The CMP operator
performs a non-destructive subtraction operation of its source operand from its
destination operand. This subtraction does not affect any of the two operands.
However, it only affects a CPU status flag. In this case, 5 compared with 5 is equal
as such the CF is not set. The JNC condition will only jump to L2 if the CF is not set.
However, in this regard the CF is not set as such the value 6 is moved to register bx.

In-text Question 3: Which flag is affected by the JNC instruction in assembly language?
Answer: The Zero flag

110
2.1.3 Jump If Zero
This type of jump checks to see whether the ZF is set. If the ZF flag is set, the jump
happens. Otherwise the jump will not occur. The ZF is set if the result of a
comparison operation equals 0, otherwise it is cleared.

Example 3

include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib
includelib C:\Irvine\Kernel32.Lib
includelib C:\Irvine\User32.Lib

.data

.code
Main PROC
mov ax,5
cmp ax,5
jz L2
mov bx,1
call Clrscr
call DumpRegs ; display registers
Exit
L2:
mov bx,6
call Clrscr
call DumpRegs ; display registers
exit
Main ENDP
END main

Note that in example 3, 5 is moved into the ax register. The CMP operator performs
a non-destructive subtraction operation of its source operand from its destination
operand. This subtraction does not affect any of the two operands. However, it only
affects a CPU status flag. In this case, the result of 5-5 becomes 0 as such the ZF is
set to 1. This makes the JZ condition true as such the CPU jump to L2 and move 6 to
register bx. However, if ZF is not set, the next instruction after the jump condition
continues executing.
111
In-text Question 4: Which flag is affected by the JZ instruction in assembly language?
Answer: The zero flag

2.1.4 Jump If Not Zero


This type of jump also checks whether the ZF is set or not. If the ZF flag is not set,
the jump happens. Otherwise the jump will not occur

Example 4

include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib
includelib C:\Irvine\Kernel32.Lib
includelib C:\Irvine\User32.Lib

.data

.code
main PROC
mov ax,5
cmp ax,5
jnz L2
mov bx,1
call Clrscr
call DumpRegs ; display registers
exit
L2:
mov bx,6
call Clrscr
call DumpRegs ; display registers
exit
Main ENDP
END main

Note that in example 4, 5 is moved into the ax register. The CMP operator performs
a non-destructive subtraction operation of its source operand from its destination
operand. This subtraction does not affect any of the two operands. However, it only

112
affects a CPU status flag. In this case, the result of 5-5 becomes 0 as such the ZF is
set to 1. The JNZ condition will only jump to L2 if the ZF is not set. However, in this
regard the ZF is set as such 1 is move to register bx.

In-text Question 5: Which flag is affected by the JNZ instruction in assembly language?
Answer: JE, JNE, JCX

2.2 Jump Based On Equality


Conditional jumps based on equality are jumps that will only be made if the value of
a source operand is equal to a value of the destination operand. These conditional
jumps are usually used with the comparison instruction (CMP). Some of the
conditional instructions are the JE, JNE, and JCXZ.

2.2.1 Jump If Equal (JE)


The JE condition jumps to label in a program if the value of a source operand is
equal to a value of the destination operand.

Example 5

include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib
includelib C:\Irvine\Kernel32.Lib
includelib C:\Irvine\User32.Lib

.data

.code
Main PROC
Mov ax,100
Cmp bx,100
je L2
Mov dx,1
Call Clrscr
Call DumpRegs ; display registers
Exit
L2:
113
Mov dx,6
Call Clrscr
Call DumpRegs ; display registers
Exit
Main ENDP
END main

2.2.2 Jump If Not Equal


The JNE condition jumps to label in a program if the value of a source operand is not
equal to a value of the destination operand.

Example 6

Include C:\Irvine\Irvine32.inc
Includelib C:\Irvine\Irvine32.lib
Includelib C:\Irvine\Kernel32.Lib
Includelib C:\Irvine\User32.Lib

.data

.code
Main PROC
mov ax,100
cmp bx,100
jne L2
mov dx,1
call Clrscr
call DumpRegs ; display registers
exit
L2:
Mov dx,6
call Clrscr
call DumpRegs ; display registers
exit
Main ENDP
END main

114
2.2.3 Jump If CX Is Not Equal Zero
The JCXZ condition jumps to label in a program if the value of in the CX register
equal zero.

Example 7

include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib
includelib C:\Irvine\Kernel32.Lib
includelib C:\Irvine\User32.Lib

.data

.code
main PROC
mov cx,1
mov bx,1
sub cx,bx
jcxz L2
mov dx,1
call Clrscr
call DumpRegs ; display registers
exit
L2:
mov dx,6
call Clrscr
call DumpRegs ; display registers
exit
main ENDP
END main

In-text Question 6: List three examples equality jump instructions of in


assembly language?
Answer:

115
2.3 Jump Based Of Unsigned Comparison

UNSIGNED JUMPS
Condition equivalent mnemonic jump condition
condition
 not  JA , JNBE CF = 0 and ZF = 0
 not  JAE , JNB CF = 0
 not  JB , JNAE CF = 1
 not  JBE , JNA CF = 1 or ZF = 1

Jumps based on comparisons of unsigned numbers are shown above. The operand
names reflect the order of operands, as in the expression (leftOp <rightOp). The
jumps in the table are only meaningful when comparing unsigned values. Signed
operands use a different set of jumps.

In-text Question 7: List three examples unsigned jump instructions of in assembly


language?
Answer: JA, JAE, JB

2.4 Jump Based Of Unsigned Comparison

SIGNED JUMPS
conditio equivalent mnemonic jump condition
n condition
 not  JG , JNLE ZF = 0 and SF =
OF
 not  JGE , JNL SF = OF
 not  JL , JNGE SF  OF
 not  JLE , JNG ZF = 1 or SF 
OF

116
Jumps based on comparisons of unsigned numbers are shown above. The operand
names reflect the order of operands, as in the expression (leftOp <rightOp). The
jumps in the table are only meaningful when comparing unsigned values.

In-text Question 8: List three examples signed jump instructions of in assembly language?
Answer: JG, JGE, JB

3.0 Tutor Marked Assignments (Individual or Group)


1. With an example, explain conditional jumps as used in assembly language.
2. With an example, show the difference between the functions of JC and JNC.
3. With an example, show the difference between the functions of JE and JNE

4.0 Conclusion/Summary
At the end of this session, we have the different types of jump Instructions and
their functions in assembly language. In the next study session, you will be
learning different types of loop Instructions in assembly language.

5.0 Self-Assessment Questions


Questions
1. What type of number does the Instruction JG operates with?
2. What type of number does the Instruction JA operates with?
3. A conditional jump instruction always causes a transfer of control.
True/false
4. What status flags are checked by the JA and JNBE
6.0 Answers to Self-Assessment Questions
1. Signed Numbers
2. Unsigned Numbers
3. False
4. CF and ZF

117
7.0 Additional Activities (Videos, Animations & Out of Class activities) e.g.
a. Visit U-tube add http://bit.ly/2UcFzF6 , http://bit.ly/2NgMSqu ,
http://bit.ly/2TIsuzI , http://bit.ly/2zbmg21 , http://bit.ly/2ZeoyrI ,
http://bit.ly/2ZeoyrI. Watch the video & summarise in 1 paragraph
b. View the animation on add/site and critique it in the discussion forum
c. Take a walk and engage any 3 students on Conditional Jumps; In 2 paragraphs
summarise their opinion of the discussed topic. etc.

8.0 References/Further Readings


Irvine, Kip R., Assembly Language for x86 Processors, 7th Edition. Pearson,
2014. ISBN-13: 9780133769401 ISBN-10: 0133769402,
Hennessy, J. L, and Patterson, D. A., Computer Architecture: A Quantitative
Approach, 5th Edition. Morgan Kaufmann, 2011. ISBN-13 : 978-
0123838728 ISBN- 10 : 012383872X

118
STUDY SESSION 3
Conditional Loop Instructions
Section and Subsection Headings:
Introduction
1.0 Learning Outcomes
2.0 Main Content
2.1- Loop if zero (LOOPZ)
2.2 -Loop if equal (LOOPE)
3.0 Tutor Marked Assignments (Individual or Group assignments)
4.0 Study Session Summary and Conclusion
5.0 Self-Assessment Questions and Answers
6.0 Additional Activities (Videos, Animations & Out of Class activities)
7.0 References/Further Readings

Introduction:
You are welcome to this study session titled conditional jumps. In this session, I
will take you through different types of loop Instructions and functions in
assembly language.

1.0 Study Session Learning Outcomes


After studying this session, I expect you to be able to:
1. Understand the function of the different loop instructions in assembly language
2. Use the different loop instructions during assembly language program
development.

119
2.0 Main Content
2.1 – LOOPZ
The LOOPZ behaves similar to the LOOP instruction. The only difference is that
the LOOPZ instruction has an extra condition that the zero flag has to be set for the
loop to continue to happen. The syntax of the LOOPZ instruction is given by

LOOPZ destination
IF ECX > 0 or CX > 0 and ZF = 1: Jump to a label

This means that the loop will continue to execute in as much as ECX or CX is
greater than zero depending on the operand size you are using whether it is a 32 or 16
bit and the zero flag equals 1. Otherwise, the loop terminates.

Example 1
include C:\Irvine\Irvine32.inc
includelib C:\Irvine\Irvine32.lib
includelib C:\Irvine\Kernel32.Lib
includelib C:\Irvine\User32.Lib

.data
intArray SWORD 0,0,0,0,1,20,35,-12,66,4,0
noneMsg BYTE "A non-zero value was not found",0

.code
main PROC
mov ebx,OFFSET intArray - 2 ; point to the array
mov ecx, LENGTHOF intArray ; loop counter

L1: add ebx,2 ; point to next


Cmp WORD PTR [ebx],0 ; compare value to zero
loops L1 ; continue the loop if ZF set
jz not Found ; none found

Found: ; display the value


movsx eax,WORD PTR[ebx]

120
call WriteInt
jmp quit

Not Found: ; display "not found" message


mov edx, OFFSET noneMsg
call WriteString

quit:
call crlf
exit
Main ENDP
END main

2.2 LOOPE
The LOOPE also behaves similar to the LOOP instruction. The only difference is
that the LOOPE has the same condition with LOOPZ instruction such that the zero
flag has to be set for the loop to continue to happen. The syntax of the LOOPZ
instruction is given by

LOOPE destination
IF ECX > 0 or CX > 0 and ZF = 1: Jump to a label
This means that the loop will continue to execute in as much as ECX or CX is
greater than zero depending on the operand size you are using whether it’s a 32 or 16
bit and the zero flag equals 1. Otherwise, the loop terminates.

In-text Question 1: What are the conditions that will make LOOPZ and LOOPE to continue
executing in an assembly language program?
Answer: ECX > 0 or CX > 0 and ZF = 1

3.0 Tutor Marked Assignments (Individual or Group)


1. With an example, explain conditional loop instructions as used in assembly
language.
2. With an example, show the difference between the functions of LOOP and

121
LOOPZ.
3. With an example, show the difference between the functions of LOOP and
LOOPE.

4.0 Conclusion/Summary
At the end of this session, we have studied different types of loop Instructions and
functions in assembly language. In the next study session, you will be learning
different types of control structures in assembly language.

5.0 Self-Assessment Questions


Questions
1. When using Branching, the usual sequencing of the PC is altered. A new
instruction is loaded which is called as ______
2. What condition set the ZF to 1.
3. Assembly language programs use conditional instructions to implement
high-level statements such as IF statements and loops. True/False
6.0 Answers to Self-Assessment Questions
1. Branch target
2. If the arithmetic operation yields a zero output.
3. True

7.0Additional Activities (Videos, Animations & Out of Class activities) e.g.


a. Visit U-tube add http://bit.ly/2UcFzF6 , http://bit.ly/2ZeoyrI ,
http://bit.ly/2ZeoyrI , http://bit.ly/2TKTQpa , http://bit.ly/2Z6QMc3. Watch the
video & summarise in 1 paragraph
b. View the animation on add/site and critique it in the discussion forum
c. Take a walk and engage any 3 students on Conditional Loop Instructions; In 2
paragraphs summarise their opinion of the discussed topic. etc.

122
8.0 References/Further Readings
Irvine, Kip R., Assembly Language for x86 Processors, 7th Edition. Pearson,
2014. ISBN-13: 9780133769401 ISBN-10: 0133769402,
Hennessy, J. L, and Patterson, D. A., Computer Architecture: A Quantitative
Approach, 5th Edition. Morgan Kaufmann, 2011. ISBN-13 : 978-
0123838728 ISBN- 10 : 012383872X

123
STUDY SESSION 4
Conditional Structures
Section and Subsection Headings:
Introduction
1.0 - Learning Outcomes
2.0 - Main Content
2.1 - Block-Structured IF Statements
2.2 - Compound Expressions with AND
2.3 - Compound Expressions with OR
2.4 - WHILE Loops
2.5 - DO WHILE Loops
2.6 - FOR Loops
3.0 - Tutor Marked Assignments (Individual or Group assignments)
4.0 - Study Session Summary and Conclusion
5.0 - Self-Assessment Questions and Answers
6.0 - Additional Activities (Videos, Animations & Out of Class activities)
8.0 - References/Further Readings

Introduction:
You are welcome to this study session titled conditional structures. In this study
session, I will take you through different types of control structures in assembly
language.

1.0 Study Session Learning Outcomes


After studying this session, I expect you to be able to:
1. Explain the function of the different control instructions in assembly language
2. Use different control instructions during assembly language program development

124
2.0 Main Content
Consider a high-level language like java for example, when java code executes, it
usually executes from top to bottom. However, this behaviour can be changed by
using control structures. In java, control structures take the form of loops such as
IF statement, FOR loop, the WHILE loops and perhaps the SWITCH case
statements which all can redirect the flow of a program. For example, if a FOR loop
reaches the bottom of the loop and the condition is true, a jump is made to the top of
the loop to repeat the code over again. However, assembly language does not have
the luxury of control structures such as high-level language. Assembly language has
a much more primitive way of creating control structures. However, assembly
language programmers can easily translate logical statements written in C++/Java
into assembly language.

In-text Question 1: Assembly language programs use conditional instructions to implement


high-level statements such as IF statements and loops. True/False.
Answer: True

2.1 Block-Structured IF Statements


An IF condition is a programming conditional statement that if proved true,
performs a function. Below is a general example of if statement

IF (OP1 > OP2) {


//some code
}
Else{
//some code
}

if the condition (OP1 > OP2) is true, the program would execute the IF block.
Otherwise, the else block is executed. We consider an example of translating a
logical IF statement written in C++/Java into assembly language where OP1 and

125
OP2 are signed integers.

Example 1

If( op1 > op2 )


X = 1;
else
X = 2;

can be translated to:

mov eax,op1
cmp eax,op2
jle L1
mov X,1
jmp L2
L1: mov X,2
L2:

2.2 Compound Expressions with AND


Compound expressions are conditions in which more than one condition is
considered in order to decide whether to execute the code inside that condition.
Below is a general example of a compound expressions with AND.

IF (OP1 > OP2 && OP3 < OP4) {


//some code
} done

The condition checks to see whether the conditions OP1 is greater than OP2 and OP3
is less than OP4 in order to execute the code in the IF block. However, if either one
of the conditions is false, the code within the IF block will not be executed. In
assembly language, there are various ways of implementing compound expression
depending of the high-level language. For example, many high level languages such
as C++ use the short circuit operation. This means the condition is evaluated from
126
left to right. Thus, during evaluation, if the first condition is false then the second
condition is not checked. This is because both conditions need to be true for the code
within the IF block to be executed. Therefore, if it is determined that the first
condition in false, the second condition is skipped. This in turn saves execution time
of a program. We consider an example of translating a logical compound IF
statement with AND (&&) written in C++/Java into assembly language where OP1,
OP2, OP3 and OP4 are signed integers.

Example 2

IF (OP1 > OP2 && OP3 < OP4) {


Statement;
}Done

can be translated to:

CMP OP1,OP2
JLE Done
CMP OP3,OP4
JGE Done
Statement
Done:

In-text Question 2: What is the advantage of using a short circuit operation for evaluating compound
expressions in assembly language programs?
Answer: The advantage of using the short circuit operation is the reduction of program execution time

2.3 Compound Expressions with OR


Compound expressions are conditions in which more than one condition is
considered in order to decide whether or not to execute the code inside that
condition. Below is a general example of a compound expressions with OR.

IF (OP1 > OP2 || OP3 < OP4) {


//some code

127
}done

The condition checks to see whether the conditions OP1 is greater than OP2 or OP3
is less than OP4 in order to execute the code in the IF block. If either both conditions
are false, the code within the IF block will not be executed. However, if either one of
the conditions is true, the code within the IF block be executed. Remember the short
circuit operation. In this case, the conditions are also evaluated from left to right.
Thus, during evaluation, if the first condition is true then the second condition is not
checked. This is because only one condition needs to be true for the code within the
IF block to be executed. This in turn saves execution time of the program. However,
if the first condition is false, the second condition will be checked, if the condition
evaluates to true the code within the IF block is executed. Finally, if both conditions
are false, the code within the IF block will not be executed. Therefore, if it is
determined that one of the condition is true, the code within the IF block is executed.
We consider an example of translating a logical compound IF statement with AND
(||) written in C++/Java into assembly language where OP1, OP2, OP3 and OP4 are
signed integers.

Example 3

IF (OP1 > OP2 || OP3 < OP4) {


Statement;
}Done

can be translated to:

CMP OP1,OP2
JGL2
CMP OP3,OP4
JL L2
Jmp Done
L2: Statement

128
Done:

In-text Question 3: What is a compound expression in assembly language programs?


Answer: Compound expressions are conditions in which more than one condition is considered in
order to decide whether to execute the code inside that condition.

2.4 WHILE Loops


A WHILE loop is a control statement that allows the repeated execution of the
same section of code a number of times based on a given Boolean condition.
The WHILE loop behaves like a repetitive IF statement. Below is a general
example of a WHILE statement.
WHILE (OP1 > OP2) {
//while body
}//done

We consider an example of translating a logical WHILE loop written in C++/Java


into assembly languagewhere OP1 and OP2 are signed integers.

Example 4

While ( op1 > op2 ) {


X = 1;
X = 2;
}
can be translated to:

START: CMP OP1, OP2


JG WHILE_BODY
JMP END_WHILE
WHILE_BODY:
mov X,1
mov Y,2
JMP START
END_WHILE:
129
In-text Question 4: What is a WHILE loop in assembly language?
Answer: A WHILE loop is a control statement that allows the repeated execution of the same
section of code a number of times based on a given Boolean condition.

2.5 DO WHILE Loops


A DO WHILE loop is a control statement that allows the execution of a section of
code at least once and then repeatedly executes the same section of code a number
of times based on a given Boolean condition. Below is a general example of a DO
WHILE statement.
DO {
//while body
} WHILE (OP1 > OP2)
//done

We consider an exampleof translating a logical Do WHILE loop written in


C++/Java into assembly languagewhere OP1 and OP2 are signed integers.

DO
mov X,1
mov Y,2
WHILE(OP1 < OP2)

can be translated to:

START: mov X,1


mov Y,2
CMP OP1, OP2
JL START

In-text Question 5: What is a DO WHILE loop in assembly language?


Answer: A DO WHILE loop is a control statement that allows the execution of a section of code
at least once, and then repeatedly executes the same section of code a number of times based on
a given Boolean condition.

130
2.6 FOR Loops
A FOR loop can be seen as a shorthand way of writing a WHILE loop. That is a
certain kind of WHILE loop that is written over and over again. Below is a general
example of a FOR loop statement

for( i = 0; i < 100; i++ )


{
//some code
}done

We consider an exampleof translating a logical Do WHILE loop written in


C++/Java into assembly language where OP1 and OP2 are signed integers.

for( i = 5; i < 100 ; i++ )


{
statement;
}

Can be translated to the assembly language code below assuming bl register is


not modified

MOV BL, 5
START: CMP BL, 100
JGE END_FOR
statement
INC BL
JMP START
END_FOR:

3.0 Tutor Marked Assignments (Individual or Group)


1. Explain the concept of block structured IF statement as used in assembly
language.
2. What is a compound expression?
3. Differentiate between a WHILE and a DO WHILE loop as used in assembly

131
language.

4.0 Conclusion/Summary
At the end of this study session, we have studied the different types of Control
Instructions in assembly language.

5.0 Self-Assessment Questions


Questions
1. Translate the pseudo code below written in high-level language into assembly
language using the short circuit evaluation.
if (al > bl) AND (bl > cl)
X=1
end if
2. Translate the pseudo code below written in high-level language into assembly
language.
while( val1 < val2 )
{
val1++;
val2--;
}

6.0 Answers to Self-Assessment Questions


1.
cmp al,bl
ja L1
jmp next
L1: cmp bl,cl
ja L2
jmp next
L2: mov X,1
Next

2.
132
mov eax,val1 ; copy variable to EAX
beginwhile:
cmp eax,val2 ; if not (val1 < val2)
jnl endwhile ; exit the loop
inc eax ; val1++;
dec val2 ; val2--;
jmp beginwhile ; repeat the loop
endwhile:
mov val1,eax

7.0 Additional Activities (Videos, Animations & Out of Class activities) e.g.
a. Visit U-tube add http://bit.ly/2UcFzF6 , http://bit.ly/2Z6QMc3 ,
http://bit.ly/30gGR0M , http://bit.ly/2NgMSqu , http://bit.ly/2NgMSqu ,
http://bit.ly/2P47VPM ,. Watch the video & summarise in 1 paragraph
b. View the animation on add/site and critique it in the discussion forum
c. Take a walk and engage any 3 students on Conditional Structures; In 2
paragraphs summarise their opinion of the discussed topic. etc.

8.0 References/Further Readings


Irvine, Kip R., Assembly Language for x86 Processors, 7th Edition. Pearson,
2014. ISBN-13: 9780133769401 ISBN-10: 0133769402,
Hennessy, J. L, and Patterson, D. A., Computer Architecture: A Quantitative
Approach, 5th Edition. Morgan Kaufmann, 2011. ISBN-13 : 978-
0123838728 ISBN- 10 : 012383872X
xiii. GLOSSARY

Term Definition
A
Addition Act of adding one thing to another
B
Binary Consisting of two (units or components or elements or terms) or
based on two

133
Bit The smallest unit of information on a machine
Bit Rate The ratio of the number of bits that are transferred between
devices in a specified amount of time, typically one second
Boolean A combinatorial system devised by George Boole that
combines propositions with the logical operators AND and OR
and IF THEN and EXCEPT and NOT
Byte A unit of storage capable of holding a single character
C
cache RAM memory that is set aside as a specialized buffer storage
that is continually updated
Clock Speed The speed at which a microprocessor executes instructions
D
Data A collection of facts from which conclusions may be drawn
Decimal A proper fraction whose denominator is a power of 10
digital A circuit or device that represents magnitudes in digits
H
Hexadecimal A number system having 16 as its base
I
Instruction The time period during which one instruction is fetched from
Cycle memory and executed when a computer is given an instruction
in machine language
Interpretation written communication in a second language having the same
meaning as the written communication in a first language
L
Logic Gate A type of circuit (or collection of transistors and resistors) that
regulates the flow of electricity (or optical signals in fibre optic
computing systems) that determines the Boolean logic
computers use to make complex logical decisions.
Logical Refers to any Boolean logic operation
M
memory An electronic memory device
N
Number A numeral or string of numerals that is used for identification

O
Operations Having to do with execution

134
P
Parallel The simultaneous use of more than one CPU to execute a
Processing program
programmer A person who designs and writes and tests computer programs

S
Stack A special type of data structure in which items are removed in
the reverse order from that in which they are added, so the most
recently added item is the first one removed. This is also called
last-in, first-out (LIFO)
Subtraction The act of subtracting (removing a part from the whole)

T
Truth Table A truth table is a logically-based mathematical table that
illustrates the possible outcomes of a scenario. The truth table
contains the truth values that would occur under the premises of
a given scenario

V
Virtual A self-contained operating environment that behaves as if it is a
Machine separate computer

135

You might also like