0% found this document useful (0 votes)
56 views97 pages

Coal Lab Manual

Computer organization and assembly language, instructions to download jdk and mars to run assembly language based MIPS

Uploaded by

princezaid2013
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views97 pages

Coal Lab Manual

Computer organization and assembly language, instructions to download jdk and mars to run assembly language based MIPS

Uploaded by

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

DS Department Computer Organization & Assembly language

Laboratory Manual

COMPUTER ORGANIZATION

&&

ASSEMBLY LANGUAGE

DEPARTMENT OF Data Science Department

UNIVERSITY OF Management and Technology, Lahore

Prepared By

EnGR. TANZEELA SHAKEEL

UMT,Lahore Page 1
DS Department Computer Organization & Assembly language

LAB 1

,INTRODUCTION WITH ASSEMBLY LANGUAGE

& Turbo ASSEMBLER, linker

Debugger

UMT,Lahore Page 2
DS Department Computer Organization & Assembly language

In this Lab You will learn

⮚ To study assembler
⮚ MASM
⮚ NASM
⮚ TASM
⮚ Emulator
⮚ Linker
⮚ DOS Debugger
⮚ Turbo Assembler
⮚ Assembly Language Syntax
⮚ How to represent number and Character
⮚ How to declare variable, arrays and define constants
⮚ Few basic Assembly Language Instruction
⮚ Lab Task

UMT,Lahore Page 3
DS Department Computer Organization & Assembly language

Theory

Assembly Language
An assembly language is a low-level programming language for computers, microprocessors,
Microcontrollers, and other integrated circuits. It implements a symbolic representation of the
binary machine codes and other constants needed to program a given CPU architecture. This
representation is usually defined by the hardware manufacturer, and is based on mnemonics that
symbolize processing steps (instructions), processor registers, memory locations, and other
language features. An assembly language is thus specific to certain physical (or virtual) computer
architecture.

Assembler
It is a system program which converts the assembly language program instructions into
machine executable instructions. For example: Microsoft Macro Assembler (MASM), Borland
Turbo Assembler (TASM), Open Source Netwide Assembler (NASM) etc.

MASM
The Microsoft Macro Assembler (MASM) is an x86 assembler for MS-DOS and Microsoft
Windows. It supports a wide variety of macro facilities and structured programming idioms,
Including high-level functions for looping and procedures. Later versions added the capability of
producing programs for Windows.

TASM
Turbo Assembler (TASM) is an x86 assembler package developed by Borland. It is used with
Borland's high-level language compilers, such as Turbo Pascal, Turbo Basic and Turbo C. The
Turbo Assembler package is bundled with the linker, Turbo Linker, and is interoperable with the
Turbo Debugger.

NASM
The Net wide Assembler (NASM) is an assembler and disassembler for the Intel x86
architecture. It can be used to write 16-bit, 32-bit (IA-32) and 64-bit (x86-64) programs. NASM
is considered to be one of the most popular assemblers for Linux and is the second most popular
assembler overall, behind MASM.
NASM was originally written by Simon Tatham with assistance from Julian Hall, and is
currently maintained by a small team led by H. Peter Anvin.

Emulators

Emulator allows computer programs to run on a platform (computer architecture and/or


operating system ) other than for which they were originally developed unlike the simulation
which only attempts to reproduce a program's behavior ,emulation attempts to model to various
degrees the state of the device being emulated.

UMT,Lahore Page 4
DS Department Computer Organization & Assembly language

EMU8086 is an emulator which emulates the behavior of 8086 machine.Emu8086 IDE contains
a built-in assembler which is compatible with the syntax of MASAM, TASAM and few other
assemblers.

It also contains a debugger which can be used to debug executable programs. In emu8086 one
can emulate each instruction of the program one by one and can view the value of registers, flags
and variables changed by instruction.

Linker

Linker or link editor is a program that takes one or more objects generated by a compiler and
combines them into a single executable program. When a program comprises multiple object
.files, the linker combines these files into a unified executable program

Linkers can take objects from a collection called a library. Some linkers do not include the whole
library in the output; they only include its symbols that are referenced from other object files or
.libraries

DOS Debugger

Debug” is a command in DOS, MS-DOS, OS/2 and Microsoft Windows (only x86 versions)“
which runs the program debug.exe (or DEBUG.COM in older versions of DOS). Debug can act
as an assembler, disassemble, or hex dump program allowing users to interactively examine
memory contents in assembly language, make changes, and selectively execute COM, EXE and
.other file types

UMT,Lahore Page 5
DS Department Computer Organization & Assembly language

TURBO ASSEMBLER

The basic steps required to create, assemble, link and debug programs using MS
Notepad and the Borland Turbo C tools TASM, TLINK and TDEBUG, respectively. Each step
requires certain command parameters and programs to be run in order to accomplish on-line
.debugging

Step 1

Creating an Assembly Language Program

An assembly language program should be entered with any text editor and have the extension
.filename.asm

Step 2

Assembling a Program

Once you have entered this program you need to assemble it. This is done using the following
TASM command line syntax.

TASM Filename.asm

The .asm extension is assumed for the file. The files generated by this command will be;

Filename.asm the source file


Filename.obj generated by TASM
Filename.lst the list file

Step 3
Linking a program
As a final step you need to run the Turbo linker (TLINK) to create an EXE (executable) file by
the name of filename.exe. This is done by entering the following command.
TLINK Filename.obj

The .obj extension is assumed for the file. The files generated by this command will be;

Filename.exe the Executable file

UMT,Lahore Page 6
DS Department Computer Organization & Assembly language

Step 4

Running DEBUG
TD, the Turbo Debugger, is run with the following command.
TD Filename.exe
Step 5

Execution of Program

The execution of the program is done by entering the following command.


Filename.exe

Assembly Language Syntax

An assembly instruction or assembler directives can have up to four fields:

Name Operation operands(s) comment

For Example:

START: MOV CX,5 ; initialize CX Register(Assembly instruction)

MAIN PROC (Assembler Directive)

Representing numbers and Character in Assembly Language

1010B Binary Representation

101D decimal Representations

ABCH Hex Representation

'A' Character Representation

"HELLO" String Representation

Characters are translated to corresponding ASCII Code by assembler, so there is no difference


between using 'A' and 41h (ASCII code for "A") in a Program.

Defining Variables, Arrays and Constants

The syntax of assembler directives that define variables is given below :

Name DB initial_value where pseudo-op DB stands for "Define Byte"

Name DW initial_value where pseudo-op DW stands for "Define Word"

UMT,Lahore Page 7
DS Department Computer Organization & Assembly language

For example :

Var1 DB 4 define a byte variable with initial value 4

Var1 DW 40 define a word variable with initial value 40

The ? in place of initial_value sets aside an uninitialized byte

ARRAYS
In assembly language an array is just a sequence of memory bytes or words. For example to
define a 3 byte array with name arr_3byte whose initial values are 10h , 20h ,30h we can write
as:

Arr_3byte DB 10h,20h,30h

The name arr_3byte is associated with the first of these bytes i.e 10h , arr_3byte+1 with second
i.e 20h , arr_3byte+2 third i.e 30h.

String of character could be initialized as:

Str DB 'ABC' or equivalently str DB 41h, 42h,43h

Msg DB 'HELLO',0AH,0DH,'$' is equivalently to msg DB 48h,45h,4ch,4fh,0Ah,0Dh,24h

Constant:

To assign a name to a constant use EQU (pseudo-op). The syntax is:

Name EQU constant

For example the following statement associates the name LF with 0Ah

LF EQU 0Ah now L could be used in place of constant 0AH which is ASCII value of
Line Feed Character.

FEW BASIC ASSEMBLY LANGUAGE INSTRUCTIONS

adc Add with carry flag


add Add two numbers
and Bitwise logical AND
call Call procedure or function
cmp Compare two operands
dec Decrement by 1
div Unsigned divide

UMT,Lahore Page 8
DS Department Computer Organization & Assembly language

idiv Signed divide


imul Signed multiply
inc Increment by 1
int Call to interrupt procedure
jmp Unconditional jump
lea Load effective address offset
mov Move data
mul Unsigned multiply
neg Two's complement negate
nop No operation
not One's complement negate
or Bitwise logical OR
pop Pop word from stack
popf Pop flags from stack
push Push word onto stack
pushf Push flags onto stack
sbb Subtract with borrow
shl Bitwise left shift (same as sal)
shr Bitwise right shift (unsigned)
sub Subtract two numbers
xor Bitwise logical XOR

Lab Task

Task # 1:
● Copy the notepad file and save the file in c:\temp folder with extension .asm i.e.
First_program.asm
● Then go to the command prompt by writing cmd
● Execute the .asm file saved above by writing the instruction tasm ,tlink
● Observe the output

UMT,Lahore Page 9
DS Department Computer Organization & Assembly language

LAB 2

INTRODUCTION to Exe template

And program structure

In this lab you will learn:

▪ Program Segment Directives

● Memory Model

● Code Segment

● Data Segment

● Stack Segment

▪ Data variable

▪ Program Segment Structure

▪ The Template of an EXE-Format Program

▪ Lab Task

UMT,Lahore Page 10
DS Department Computer Organization & Assembly language

Program Segment Directives


The key simplified segment directives are STACK_SEG, CODE_SEG, DATA_SEG,
.MODEL.

Memory Models

The .MODEL directive specifies the memory model for an assembler module that uses the
simplified segment directives. The .MODEL directive must precede .CODE, .DATA, and
.STACK. The format of the .MODEL directive is:

MODEL memory model.


The memory model can be TINY, SMALL, COMPACT, MEDIUM, LARGE, HUGE.

TINY One segment. Thus both program code and data together must fit within
the same 64 Kb segment. Both code and data are near.

SMALL Program code must fit within a single 64 Kb segment, and data must fit
within a separate 64 Kb segment. Both code and data are near.

MEDIUM More than one code-segment. One data-segment. Thus code may be
greater than 64K.

COMPACT One code-segment. More than one data-segment. Thus data may be greater
than 64K.

LARGE More than one code-segment. More than one data-segment. No array larger
than 64K. Thus both code and data may be greater than 64K.

HUGE More than one code-segment. More than one data-segment. Arrays may be
larger than 64K. Thus both code and data may be greater than 64K

UMT,Lahore Page 11
DS Department Computer Organization & Assembly language

All program models but TINY result in the creation of exe-format programs. The TINY
model creates com-format programs.

Stack Segment

STACK_SEG defines the stack segment and controls the size of the stack. For example,

STACK_SEG segment STACK 200h

Defines stack 200h (512) bytes long.

Code Segment

CODE_SEG marks the start of your program’s code segment. It contains executable instruction.

Main PROC

; Here the lines of executable instructions.

Main endp

CODE_SEG ends

Data Segments

DATA_SEG marks the start of your data segment. You should place your memory variables in
this segment. For example,

DATA_SEG segment ‘data’

Coal db "Welcome to coal"

DATA_SEG ends

• CS: points to the beginning of the code segment


• DS: points to the beginning of the data segment
• SS: points to the beginning of the stack segment

UMT,Lahore Page 12
DS Department Computer Organization & Assembly language

DATA VARIABLES

symbolic addresses of data items (offsets in the data segment)

Defined by directives DB, DW, DD, DQ

Format for data definition

]name] Dx expression

Coal DB “this is my first program”

Directive Dx:

● determines the variable type (according to the letter x)


● allocates the space in memory (one or more bytes)
● Initializes the contents of the memory locations (does not Initialize, if the expression
is?)

Expression:

can be uninitialized : ?

Can be assigned a constant: such as 25, 21.

Example:

DATAZ DB 21, 2

Allocated Variable type Variable may contain


Directive memory
size in bytes

Signed integer in the range


DB 1 BYTE <-128; 127>
Unsigned integer in the range
<0; 255> Character
Signed integer in the range
DW 2 WORD <-32 768; 32 767>
Unsigned integer in the range
<0; 65 535> 16-bit offset

UMT,Lahore Page 13
DS Department Computer Organization & Assembly language

Signed integer
DD 4 Double Word Unsigned integer
Single precision floating point
number in the range about
±10^38
Far pointer in 16-bit mode, i.e.
address in the segment: offset
form 32-bit offset
Signed integer
DQ 8 Quad Word Unsigned integer
Double precision floating point
number in the range about
±10^308

Program Segment Structure

● Select a memory model

● Define the stack size

● Define data segment

● Declare variables

● Define code segment

● Write code

● organize into procedure

● Mark the end of the source file

● define the entry point

The Template of an EXE-Format Program

The following exe-format display the string “This is my First Program” on screen

.model small

UMT,Lahore Page 14
DS Department Computer Organization & Assembly language

data_Seg segment 'data'

; Add your Data here

st1 db "this is my first program",13,10,'$'

data_Seg ends

Code_Seg segment 'code'

assume cs:code_Seg, ds:data_Seg, ss:stack_seg

main proc far

; Set Segment Registers

mov ax,data_Seg

mov ds,ax

; Add Your Code Here

mov ah,9

mov dx,offset st1 ;string display

INT 21h

;exit to operating system

MOV AH,4CH

INT 21h

MAIN endp

code_seg ends ; set entry point and stop the assembler

stack_Seg segment stack

db 100h dup (?)

stack_Seg ends

end main

UMT,Lahore Page 15
DS Department Computer Organization & Assembly language

LAB TASKS
Task # 1:

1. Copy the above code in notepad and save the file with extension .asm i.e.
First_program.asm
2. Then go to the command prompt by writing cmd
3. Execute the .asm file saved above by writing the instruction TASM ,TLINK
4. Observe the output

Task # 2:

1. Declare two or three strings in data segment of above code as str1 db “First String
”,13,10,”$”
2. Display these two or three strings one by one on the output screen by using the String
Display Output Instruction in Turbo Assembler (TASM) or Emu 8086
3. Observe the output

UMT,Lahore Page 16
DS Department Computer Organization & Assembly language

LAB 3

INTRODUCTION to INPUT / OUTPUT INSTRUCTION

IN THIS LAB YOU WILL LEARN:

● DOS/ IO Service Routine


● INT Instruction
● How to read Character input with Echo
● How to display a Character
● How to read Character input without Echo
● How to Display String
● Data movement and Arithmetic instruction
● LAB TASK

UMT,Lahore Page 17
DS Department Computer Organization & Assembly language

DOS /IO service Routines

CPU communication with peripherals devices through I/O registers called I/O ports.
There are two instructions, IN and OUT, that access the ports directly. These Instructions are
used when a program needs to directly communicate with peripherals like when fast I/O is
needed.
These are two categories of I/O service routines

(i) BIOS Routines

BIOS routines are stored in ROM and communicate directly with I/O ports.

(ii) DOS Routines

The DOS routines actually use The BIOS routines to perform direct I/O operation. They Can
carry out the more Complex tasks; for example printing a character string, getting inputs from
keyboard etc.

INT instruction

To invoke DOS or BIOS routine, the INT (interrupt) instruction is used, it has the format

INT interrupt number

When an Interrupt number is a number that specifies a routine, for example INT 16h invokes a
BIOS routine that performs keyboard input. INT 21h may be used to invoke a large number of
DOS functions.

Interrupts Recommended:

1) INT 21H, Function 04CH terminate the code properly and return to the DOS Prompt.
2) INT 21H, Function 02H Display a number or character on the screen.
3) INT 21H, Function 09H Display the string on the screen
4) INT 21H, Function 01H Get Character input with Echo.
5) INT 21h, function 08H Get Character input without Echo.

UMT,Lahore Page 18
DS Department Computer Organization & Assembly language

Function 01 - Read a character input with Echo from keyboard

Reads a character from the standard input device and echoes it to the standard output device.
If no character is ready it waits until one is available.

To get input from the keyboard, execute the following instruction.

MOV ah, 01H; input key function

INT 21H; get ASCII code in AL

On entry: Ah= 01H


Returns: AL= 8 bit data input.

When a character is pressed, AL will contain its ASCII code if any other key is pressed, such as
.an arrow key or F0-F10 and so on, AL will contain 0

Function 02 - Display a Character on Screen

To display a character “A‟ on screen execute the following instruction, actually DL must contain
the ASCII code of Character that is to be displayed. In this example DL will contain ASCI code
of “A‟.

MOV AH, 2; display character function

MOV DL, “A‟; character is “A

INT 21H ; display character

:On entry AH = 02h


)DL = 8 bit data (usually ASCII character

:Returns Nothing

Function 08 - Read a character input without Echo from keyboard

Reads a character from the standard input device without copying it to the display. If no
.character is ready it waits until one is available

MOV AH, 08h ; Input key function

.INT 21h ; get ASCII code in AL

UMT,Lahore Page 19
DS Department Computer Organization & Assembly language

On entry: Ah= 01H


Returns: AL= 8 bit data input.

Function 09 - Display a string on Screen

To display a String execute the following instruction, DX register must contain the starting offset
Address of string that to be displayed

LEA DX, msg; get offset address of msg

OR

MOV DX, offset msg ; get offset address of msg.

MOV AH, 9; string Display function


Int 21h; Display msg

On entry Ah= 09H


DS: DX = segment: offset of string

Returns: Nothing.

Where msg is string define in Data Segment as

Msg db ‟hello world‟, 0Ah, 0Dh, “$‟ or


Msg db “hello world” ,13h,10h,24h

The string must be terminated by the $ character (24h), which is not transmitted. Any ASCII
code can be embedded within the string.

Data movement and Arithmetic instruction

In 8086 General purpose registers are:

ax, bx, cx, dx

These four 16-bit registers can also be treated as eight 8-bit registers:

UMT,Lahore Page 20
DS Department Computer Organization & Assembly language

ah, al, bh, bl, ch, cl, dh, dl

Assignment

In C, assignment takes the form:

C Syntax Assembly syntax

x = 42 ; mov x,42

y = 24; mov y, 24

z = x + y; add z,x

add z ,y

In assembly language we carry out the same operation but we use an instruction to denote the
assignment operator ("=" in C).

OPCODE destination, source


Operation Operand, Operand

MOV Register, register


MOV register, immediate value
Add register, register
Add register, immediate value

Print “Hello Word ” by String

.model small

stack_Seg segment stack

db 100h dup (?)

stack_Seg ends

Data_seg segment ‘data’


Msg db 'Hello world',0Ah,0Dh,'$'
msg1 db 'Coal',0Ah,0Dh,'$'

data_seg ends

UMT,Lahore Page 21
DS Department Computer Organization & Assembly language

Code_seg segment ‘code’

assume cs:code_Seg, ds:data_Seg, ss:stack_seg


Main proc
Mov ax,data_seg ; get data segment
Mov ds,ax

; initialize DS

Mov dx ,offset msg ;get first msg

; You also can use “LEA DX,msg” instead of ” mov dx , offset msg” ; get offset address of msg

Mov ah,09 ; display string


Int 21h ;do it

LEA dx , msg1 ;get offset address of 2nd msg


mov ah,09 ; display string
int 21h ;do it

;terminate dos
Mov ah ,04Ch ;dos exit
Int 21h

Main endp
Code_seg ends
End main

UMT,Lahore Page 22
DS Department Computer Organization & Assembly language

Lab Task # 1:

1. Print your Name


2. Print your Registration ID
3. Print your section
4. Output in following format:

Name: xyz
ID: 1234
Section: B

Lab Task # 2:

1. Prompt User to Enter 1st (1-digit) number


2. Prompt User to Enter 2nd (1-digit) number
3. Add two numbers
4. Display result in the following format:

“The sum of 2 and 7 is 9”

Lab Task # 3:

1. Prompt user to enter a lower case letter character


2. Convert it into Upper Case character
3. Output the result in the following format:

“Lower case f converted to uppercase F”

UMT,Lahore Page 23
DS Department Computer Organization & Assembly language

LAB 4

FLAG STATUS REGISTER

IN THIS LAB YOU WILL LEARN:

● Conditional Flags
o Carry flag
o Sign flag
o Overflow flag
o Zero flag
o Auxiliary flag
o Parity flag
● Control Flags
o Trap flag
o Interrupt flag
o Directional flag
● LAB TASK

UMT,Lahore Page 24
DS Department Computer Organization & Assembly language

Flag Register

The 8086 flag register contents indicate the results of computation in the ALU. It also contains
some flag bits to control the CPU operations.

A flag can only take on the values 0 and 1. We say a flag is set if it has the value 1.

A 16 flag register was used in 8086. It is divided into two parts.

(a) Condition code or status flags

(b) Machine control flags

The condition code flag register is the lower byte of the 16-bit flag register. The condition code
flag register is identical to 8085 flag register, with an additional overflow flag.

The control flag register is the higher byte of the flag register. It contains three flags namely
direction flag (D), interrupt flag (I) and trap flag (T).

The complete bit configuration of 8086 is shown in the figure.

X X X X O D I T S Z X A X P X C
C Y

S- Sign Flag: This flag is set, when the result of any computation is negative.

Z- Zero Flag: This flag is set, if the result of the computation or comparison performed by the
previous instruction is zero.

P- Parity Flag: This flag is set to 1, if the lower byte of the result contains an even number of
1’s.

C- Carry Flag: This flag is set, when there is a carry out of MSB in case of addition or a borrow
in case of subtraction.

T- Tarp Flag: If this flag is set, the processor enters the single step execution mode.

I- Interrupt Flag: If this flag is set, the mask-able interrupts are recognized by the CPU,
otherwise they are ignored.

D- Direction Flag: This is used by string manipulation instructions. If this flag bit is ‘0’, the
string is processed beginning from the lowest address to the highest address, i.e., auto
incrementing mode. Otherwise, the string is processed from the highest address towards the
lowest address, i.e., auto incrementing mode.

UMT,Lahore Page 25
DS Department Computer Organization & Assembly language

AC-Auxiliary Carry Flag: This is set, if there is a carry from the lowest nibble, i.e, bit three
during addition, or borrow for the lowest nibble, i.e, bit three, during subtraction.

O- Overflow Flag: This flag is set, if an overflow occurs, i.e, if the result of a signed operation
is large enough to accommodate in a destination register. The result is of more than 7-bits in size
in case of 8-bit signed operation and more than 15-bits in case of 16-bit sign operations, and then
the overflow will be set.

Flags When it's Set(1)

CF—Carry Flag when there is an unsigned overflow

PF---Parity Flag when there is even number of one bits in result

AF---Auxiliary Flag when there is an unsigned overflow for low nibble (4 bits)

ZF---Zero Flag when result is zero

SF---Sign Flag when result is negative

TF---Trap Flag Used for on-chip debugging

IF—Interrupt Enable Flag - when this flag is set to 1 CPU reacts to interrupts from external devices

DF---Direction Flag this flag is used by some instructions to process data chains, when this flag
is set to 0 - the processing is done forward, when this flag is set to 1the
processing is done backward

OF---Overflow Flag when there is a signed overflow

UMT,Lahore Page 26
DS Department Computer Organization & Assembly language

LAB TASK

Execute the following Programs in Turbo Debugger and fill the output table with corresponding
value of register and give the reason if the value of flag is set to 1.

Program 1: [Assume registers are set to default values]

Mov ah,07Fh
Output:
Mov ax,1234

Mov bh,al AX =
AX =
Mov bl,ah BX =
BX=

Program 2: [Assume registers are set to default values]

Mov al,81 Output:


Add al,0FEh
AX =
AX =
FLAG BITS :

Program 3: [Assume registers are set to default values]

Mov ax,5510
Sub al,2

Output:

AX =
AX =
FLAG BITS :

UMT,Lahore Page 27
DS Department Computer Organization & Assembly language

Program 4: [Assume registers are set to default values]

Mov ah,10
Output:
Mov bh,10
Sub ah,bh AX =
BX=
FLAG BITS :

Program 5: [Assume registers are set to default values]

Mov ax,0FFFEh
Output:
Sub al,2
Mov bx,02D8Ch AX =
Add bx,ax AX =
FLAG BITS :
BX=
BX=
FLAG BITS :

Program 6: [Assume registers are set to default values]

Mov al,100
Add al,50
Output:

AL=
FLAG BITS :

UMT,Lahore Page 28
DS Department Computer Organization & Assembly language

Program 7: [Assume registers are set to default values]

Mov ax,32760
Output:
Add ax, 50
AX=
AX=
FLAG BITS :

Program 8: [Assume registers are set to default values]

Mov ax,65530
Output:
Add ax, 80
AX=
AX=
FLAG BITS :

UMT,Lahore Page 29
DS Department Computer Organization & Assembly language

LAB 5

Introduction to gotoxy(), clrscr() & Loops

In this lab you will learn:

⮚ BIOS INT
⮚ INT 10h –services
⮚ Screen position
⮚ Setting the cursor position- goto (x,y)
⮚ Scroll page up - clrscr window
⮚ Scroll page down
⮚ Loops
⮚ Lab tasks

UMT,Lahore Page 30
DS Department Computer Organization & Assembly language

Interrupt Handler:

A callback subroutine called when an interrupt is received. Also known as Interrupt


Service Routine.

Interrupt are of two types:

1- Hardware Interrupts: A signal from some device e.g. mouse, keyboard, etc.

2- Software Interrupts: Caused by some exceptional condition or by some special


instruction in instruction set.

x8086 Software Interrupts:

The INT instruction in x8086 instruction invokes the respective ISR to perform the task
assigned. Number of interrupts supported by the instruction set is 256 but every interrupt can
have up to 256 sub interrupts. So the total number of interrupts are (256 * 256) = 65,536.

Useful DOS Interrupts

1) INT 21H, Function 04CH terminate the code properly and return to the DOS Prompt.
2) INT 21H, Function 02H Display a number or character on the screen.
3) INT 21H, Function 09H Display the string on the screen
4) INT 21H, Function 01H Get Character input with Echo.
5) INT 21h, function 08H Get Character input without Echo.

For example 21H interrupt number has 108 sub interrupts like 01H for character input, 02H for
character output etc.

UMT,Lahore Page 31
DS Department Computer Organization & Assembly language

Useful BIOS Interrupts

The following are the IBM PC BIOS interrupts in which we will be Interested.

INTERRUPT FUNCTION

a. 5H Print screen
b. 10H Video I/O
c. 11H Equipment check
d. 14H Serial I/O
e. 1BH Keyboard break
f. 1CH Timer tick
g. 1FH Graphics character table

INTERRUPT 10H is the most useful BIOS interrupt to the programmer. INT 10H is the 17th
Interrupt vector in an x86 based computer system. It is a real mode ISR. Interrupt 10H is used to
provide the standard character output function as well as to provide some additional control over
the video display.

How to Use

Like 21H it has many subroutines. So the steps involved in using this routine are

1- Load AH with the number of required subroutines.

2- Load other desired parameters

3- Call INT 10H

Some 80x25 screen position

Position Decimal Hex


Column Row Column Row
Upper left corner 0 0 0 0
Lower left corner 0 24 0 18
Upper right corner
Lower right corner 79 0 4f 0
Center of the screen 79 24 4f 18
39 12 27 C

UMT,Lahore Page 32
DS Department Computer Organization & Assembly language

INT 10h function 2 set cursor position

● Input AH = 2
● DH = new cursor row (0-24)
● DL = new cursor column 0-79 for 80x25 display,0-39 for 40x25
● Output none

Example :

o Mov dh,10
o Mov dl,20
o Mov ah, 2
o Int 10h

INT 10h function 6 scroll the screen or window up

INT 10h function 7 scroll the screen or window down

● Input AH = 6/7
● AL= number of lines to scroll (0 = whole screen)
● BH = attribute for blank lines
● DL,DH =row column for lower right corner
CL,CH = row column for upper left corner of window
● Output none

⮚ Scrolling the screen up one line means to move each display line UP one row and insert
a blank line at the bottom of the screen. The previous top row disappears from the screen.

⮚ The whole screen or any rectangular area (window) may be scrolled. AL contains the
number of lines to scroll. If AL = 0, all the lines are scrolled and this clears the screen or
window.

⮚ Function 7 Same as function 6, but lines are scrolled down instead of up.

⮚ Example: Clear the screen to black for the 80x25 display.

UMT,Lahore Page 33
DS Department Computer Organization & Assembly language

MOV AH, 6 ; scroll up function


XOR AL, AL ; clear entire screen
XOR CX, CX ; upper left corner is (0,0)
MOV DX, 184FH ; lower right corner is (4Fh, 18H)
MOV BH, 7 ; normal video attribute
INT 10H ; clear screen

Looping instruction

A loop is a sequence of instructions that is repeated the number of times to repeat may be known
.in advance, or it may depend on condition

Use the following lines to loop

MOV CX, Number Of iterations

Again: start loop here

; Instructions

LOOP Again

Lab Tasks

Task # 1

● Clear the command screen clrscr command (scroll up/down window)


● Prompt a user to enter an alphabet
● Go to the Screen Position to x=12 and y=40 by setting dh(row) and dl(column)
● Make a loop of 10 by initializing Cx=10
● Display the input character and the 9 upcoming characters in a loop defined above

Example

Enter a character: g

ghijklmnop

UMT,Lahore Page 34
DS Department Computer Organization & Assembly language

Task # 2:

● Clear the command prompt screen by using clrscr


● Prompt a user to enter an alphabet
● Go to the Screen Position to x=6 and y=20 by setting dh(row) and dl(column)
● Make a loop of 7 by initializing Cx=7
● Keeping the value of ‘y’ constant, increment in the value of ‘x’ and display the
input character as well as its upcoming characters in corresponding rows.

Example:

Enter a character: A

Task # 3:

● Clear the command prompt screen by using clrscr


● Prompt a user to enter an alphabet
● Go to the Screen Position to x=6 and y=20 by setting dh(row) and dl(column)
● Make a loop of 7 by initializing Cx=7
● Increment the value of ‘y’ , increment in the value of ‘x’ and display the input
character as well as its upcoming characters in corresponding rows and columns.

Example:

Enter a character: A

UMT,Lahore Page 35
DS Department Computer Organization & Assembly language

​Task # 4

1. Prompt User to Enter 1st (1-digit) number


2. Prompt User to Enter 2nd (1-digit) number
3. Add two numbers
4. Display result in the following format:

​Enter First Digit: 4

​Enter Second Digit:4

​ 4

​+ 4

​==========

​8

UMT,Lahore Page 36
DS Department Computer Organization & Assembly language

LAB 6

8086/8088 addressing modes

In this lab you will learn:

⮚ Addressing modes of 8086/8088


▪ Register AM
▪ Immediate Data Addressing
▪ Direct Data Addressing
⮚ INDIRECT MODE ADDRESSING
▪ Indirect mode through Base registers
▪ Indirect mode through Index registers
▪ Indirect through Sum of Base and index Registers
⮚ RELATIVE ADDRESSING MODE
▪ Relative mode through base register
▪ Relative mode through Index Register
▪ Relative mode through Sum of Base and index
Registers

⮚ Lab Task

UMT,Lahore Page 37
DS Department Computer Organization & Assembly language

Addressing Modes

The way in which an operand is specified is called the Addressing Mode. The data addressing
:modes available in 8080/8088 are following

Register Addressing mode.1


.Simplest of all addressing modes
.Specifies the source operand, destination operand or both to be contained in an 8086 register
.Transfers a copy of a byte or word from source register to destination registers
eg:- MOV AX, BX
ADD AX, BX
MOV AX, BX; 16-bit data transfer
MOV AL, BL ; 8-bit data transfer

Immediate Addressing mode.2

Transfers immediate byte or word of data into the destination Register


E.g.: MOV AX, 0FAH
ADD BX, 4
MOV AL, 45H
MOV BX, 5062H

Direct Addressing mode.3

.Address of the operand is directly specified in the instruction itself


Moves a byte or word between a memory location and a register
:E.g
MOV [1234H], AX
Suppose DS contains 1000H
Physical Address is DS X 10H + 1234H = 10000H + 1234H
11234H =
]E.g. MOV BX, [5062
bit physical address of memory location is calculated using DS and offset value 5062-20
Similarly the following instruction

MOV DATA,BP ; moves the content of BP to the memory location associated with variable
DATA.AS as a result BP is copied into memory location DATA and DATA+1 in the data
.segment

UMT,Lahore Page 38
DS Department Computer Organization & Assembly language

REGISTER INDIRECT ADDRESSING

In this mode, the offset address of the operand is contained in a register. We say that the register
acts as a pointer to memory location. The operand format is

.REGISTER] The register is BX,SI,DI or BP[

For example suppose SI contain 0100h and the word at 0100h contains 1234h.to execute

MOV AX,[SI]
:The CPU execute

● Examines SI and obtains the offset address 100h


● Use address the DS:0100h to obtain the value 1234h
● Moves 1234h to AX

Indirect Mode through Base Registers.4

Memory location is specified by Base Registers. Effective address is sum of 16-bit offset in
.given instruction
Contents of base register BX or BP
Segment register is DS or SS
]E.g. MOV AX, 4[BX
MOV [BX], CX

Indirect Mode through Index Registers.5

Memory location is specified by Index Registers. Effective address is sum of 16-bit offset
given in instruction

Contents of index register SI or DI

Segment register is DS

E.g. MOV AX, 4[SI] MOV [SI], CX

Indirect mode through Sum of Base and Index Registers

Memory location specified by sum of Base and index Registers. Effective address is sum of

bit offset given in instruction-16

Contents of index register SI or DI

Contents of base register BX or BP

UMT,Lahore Page 39
DS Department Computer Organization & Assembly language

Segment register is DS

]E.g. MOV AX, 4[BX][SI

E.g.: MOV [BX+SI], CX

Register Relative addressing

In register relative addressing the data in segment of memory are addresses by adding the
)displacement to the content a base or index register (BX, BP,DI,SI

.The syntax of the operand is any of the following equivalent expressions

✔ [register +displacement]
✔ [register]+displacement
✔ Displacement +[register]
✔ Displacement[register]
Relative mode through Base Register.7

Memory location addressed by Base register plus a displacement


MOV [BX+4], CX

Relative mode through Index Register.8

Memory location addressed by Index register plus a displacement


MOV [SI+4], CX
Relative mode through Base and Index Register.9

Memory location addressed by Base and index register plus a displacement


MOV ARRAY[BX+SI],DX

LAB TASK

1. Write an ALP to transfer a word data in different addressing modes


.model small

stack_Seg segment stack

db 100h dup (?)

UMT,Lahore Page 40
DS Department Computer Organization & Assembly language

stack_Seg ends

Data_seg segment 'data'

num dw 4321h

data_seg ends

code_seg segment 'Code'

assume cs:code_seg;ds: data_seg; ss:stack

main proc

Mov ax,data_seg

Mov ds,ax

mov dx,2222h

Mov ax,1234h ;immediate addressing

Mov bx,ax ;register addressing

Mov ax,num ;direct addressing

Mov si,1000h

mov [si],bl

Mov al,[si] ;indirect addressing

mov [si+100h],dl

Mov bl,[si+100h] ;relative addressing

Mov bx,1000h

mov [si+bx],3333h

Mov ax,[si+bx] ;base index addressing

mov [si+bx+100h],4444h

Mov cx,[si+bx+100h] ;relative base index addressing

Mov ah,4ch

Int 21h

UMT,Lahore Page 41
DS Department Computer Organization & Assembly language

Proc Endp

Code_seg ends

End main

2. Write an ALP to transfer a byte data in different addressing modes.


.model small

stack_Seg segment stack

db 100h dup (?)

stack_Seg ends

Data_seg segment 'data'

num db 4321h

data_seg ends

code_seg segment 'code'

assume cs:code_seg ; ds:data_seg;ss: stack

main proc

Mov ax,data_seg

Mov ds,ax

mov dl,22h

Mov al,12h ;immediate addressing

Mov bl,al ;register addressing

Mov al,num ;direct addressing

Mov si,1000h

mov [si],bl

Mov al,[si] ;indirect addressing

mov [si+100h],dl

Mov bl,[si+100h] ;relative addressing

UMT,Lahore Page 42
DS Department Computer Organization & Assembly language

Mov bx,1000h

mov [si+bx],33h

Mov al,[si+bx] ;base index addressing

mov [si+bx+100h],44h

Mov cl,[si+bx+100h] ;relative base index addressing

Mov ah,4ch

Int 21h

Proc Endp

Codes_seg ends

End main

Task # 2:

1. Clear the command screen clrscr command (scroll up/down window)


2. Prompt a user to enter a string of characters using indirect addressing mode
3. Go to the Screen Position to x=10 and y=20 by setting dh(row) and dl(column)
4. Print the string entered by user character by character using indirect addressing mode.

Example:
Suppose User enter a string “hello” then the output should be h e l l o

Task # 3:

5. Clear the command screen clrscr command (scroll up/down window)


6. Prompt a user to enter a string of characters using relative addressing mode
7. Go to the Screen Position to x=10 and y=20 by setting dh(row) and dl(column)
8. Print the string entered by user character by character using relative addressing mode.

Example:
Suppose User enter a string “hello” then the output should be h e l l o

UMT,Lahore Page 43
DS Department Computer Organization & Assembly language

LAB 7

8086/8088 Read an input String/ Arrays

In this lab you will learn:

⮚ Read an Input String


⮚ Lab tasks

UMT,Lahore Page 44
DS Department Computer Organization & Assembly language

Read an Input String

Following lines of code will input a string from the keyboard and save it to a buffer whose offset
address must exist in register DX and the first location of the buffer must contain the size of the
.buffer. This function does not allow entering more characters than the specified buffer Size

● LEA DX, buffer; get offset address of buffer


● ;MOV buffer, String _size
● MOV buffer ,5
● MOV Ah, 0AH ; input String Function
● INT 21h ; input String.

On entry Ah= 0AhH


DS: DX = segment: offset of string

Returns: buffer =data input

When above code executes, first byte of buffer will contain size of buffer as specified in buffer
.declaration , 2nd byte will contain actual no of character read

.must be appended at the end of the buffer to print the contents of the buffer as string ‟ $“

Buffer of size 10 can be defined as

)$‘( Buffer db 10 dup

)?( Buffer db 10,5 dup

Buffer Actual xx xx xx xx xx xx xx xx
length length

”Suppose User enter a string “hello

10 5 65 67 c6 c6 f6 d0 xx xx

Offset Size Description


00 1 maximum characters buffer can hold

UMT,Lahore Page 45
DS Department Computer Organization & Assembly language

number of chars from last input which may be recalled OR number of characters
01 1
actually read, excluding CR
02 n actual characters read, including the final carriage return

LAB TASK

Task # 1:

9. Clear the command screen clrscr command (scroll up/down window)


10. Prompt a user to enter a string of characters
11. Go to the Screen Position to x=10 and y=20 by setting dh(row) and dl(column)
12. Print the string entered by user character by character

Example:
Suppose User enter a string “hello” then the output should be h e l l o

Task # 2:

1. Clear the command screen clrscr command (scroll up/down window)


2. Prompt a user to enter String of Capital letters
3. Traverse whole string and convert it into small letters using LOOP
4. Go to the Screen Position to x=12 and y=24 by setting dh(row) and dl(column)
5. Display the new resulting string on console

Note: To convert a capital letter to a small one, use the following instruction:

ADD 20H to the register containing your Capital letter

Output:

The output should be as follow:

Enter a string of Capital Letters: ABCD

UMT,Lahore Page 46
DS Department Computer Organization & Assembly language

Converted String is: abcd

Task # 3:

1. Clear the command screen clrscr command (scroll up/down window)

2. Prompt a user to enter a string of maximum 20 size


3. Reverse this input string
4. Go to the Screen Position to x=15 and y=26 by setting dh(row) and dl(column)

5. Output the result on console

Note: The above program should be done using LOOP

Output:

The output should be like this:

Enter a String: Welcome To Coal Lab

Reversed String is: baL loaC oT emocleW

Task # 4:

1. Clear the command screen clrscr command (scroll up/down window)


2. Prompt a user to enter 1st string(array)
3. Prompt a user to enter 2nd string(array)
4. Add the two strings and save the sum in a third string(array)
5. Go to the Screen Position to x=10 and y=20 by setting dh(row) and dl(column)
6. Output the resulting string on console

Note: The above program should be done using LOOP. And the sum should not exceed 9.

Output:

The output should be like this:

Enter 1st string: 124

Enter 2nd string: 235

Resulting String is: 359

UMT,Lahore Page 47
DS Department Computer Organization & Assembly language

LAB 8

Arithmetic OPERATIOn

In this lab you will learn:

▪ Arithmetic operation
● Add instruction
● Sub instruction

▪ LAB TASK

UMT,Lahore Page 48
DS Department Computer Organization & Assembly language

Arithmetic Operation :-

Pentium provides several arithmetic instructions that operate on 8, 16, 32 bit operands.
i. Addition ADD, ADC , AAA , INC
ii. Subtraction SUB, SBB , AAB , DEC
iii. Multiplication MUL ,IMUL
iv. Division DIV ,IDIV

Addition Instructions:-
ADD
Basic format
ADD destination, source
Perform simple integer instruction
Destination = destination +source
Five operand combinations are possible:
Add register, register
Add register, immediate
Add memory, immediate
Add memory, register
Add register, memory

ADC
Basic format
ADD destination, source
Perform integer Addition with Carry
Destination = destination +source +CF

The three carry flag manipulation instruction are useful


STC Set Carry flag (cf=1)
CLC Clear Carry flag (cf = 0)
CMC Complementary Carry flag (invert cf value).

INC
INC requires a single operand
INC destination
Destination = destination +1
AAA
ASCII adjusts for addition.
Main use is in arithmetic operations on BCD numbers.AAA has no Operand (AL is assumed to
be the operand). It is used after an add operation to adjust the BCD value in AL.

Basic format
AAA

UMT,Lahore Page 49
DS Department Computer Organization & Assembly language

Subtraction instruction:-
SUB
Basic format
SUB destination, source
Perform simple integer instruction
Destination = destination - source

SBB
Basic format
SBB destination, source
Perform integer Addition with Carry
Destination = destination - source - CF

DEC
Dec Requires a single operand
DEC destination
Destination = destination -1
AAS
ASCII adjusts for Subtraction.
AAS has no Operand (AL is assumed to be the operand). It performs BCD subtraction
adjustment on AL.

Basic format
AAS

LabTasks

Task # 1:

1. Prompt User to Enter 1st (1-digit) number


2. Prompt User to Enter 2nd (1-digit) number
3. Add two numbers using ADD, ADC, and AAA instructions.
4. Display result in the following format:
“The sum of 5 and 7 is 12”

Task # 2:
1. Move a 1st 2-digit hexadecimal number to a register AL
2. Move a 2nd 2-digit hexadecimal number to a register BL
3. Add 8 –bit numbers using arithmetic instructions (Add,adc,aaa).
4. Display result in the following format:
“The sum of 53 and 36 is 89”

UMT,Lahore Page 50
DS Department Computer Organization & Assembly language

Task # 3:
1. Prompt User to Enter 1st (1-digit) number
2. Prompt User to Enter 2nd (1-digit) number
3. SUB two numbers using SUB,SBB,AAS instructions.
4. Display result in the following format:
“The sum of 37 and 32 is 5”
Task #4

Write 8086 Assembly Language programs for the following operations. The
operands and the results are to be stored in specific memory locations.
(a) Add three 16-bit unsigned integers (b)Add three 16-bit signed integers
(c)Compute the function:
X = |((A+B) – (C+D))| - E. Assume 16-bit unsigned integer variables.

UMT,Lahore Page 51
DS Department Computer Organization & Assembly language

LAB 9

Stack

STACK

● The stack is implemented for temporary storage of information such as data or addresses.
● The stack is 64KBytes long.
● The contents of the SP and BP registers are used as offsets into the stack segment
memory while the segment base value is in the SS register.
● Push instructions (PUSH) and pop instructions (POP)
● Top of the stack (TOS) and bottom of the stack (BOS)
● The 8088 can push word-wide data and address information onto the stack from registers
or memory.
● Many stacks can exist but only one is active at a time.

PUSH AX
POP AX

LAB TASK

TASK # 1

UMT,Lahore Page 52
DS Department Computer Organization & Assembly language

1. Prompt a user to enter 5 characters using AH 01h service routine


2. Push each character in a stack
3. Pop characters from this stack and insert it in a 1st string array
4. Prompt a user to enter another 5 characters using AH 01h service routine
5. Push each character in a stack
6. Pop characters from this stack and insert it in a 2nd string array
7. Now you have 2 strings of characters.
8. Merge the two strings and save it in a third string array
9. Output the resulting string on console

NOTE

Take 5 characters in a loop having cx=5

OUTPUT:

The Output should be as follow:

Enter 5 character :abcde

Enter 5 character :fghij

Merged String is:ejdichbgaf

TASK# 2

1. Prompt a user to enter a string of maximum 20 size


2. Reverse this input string
3. Output the result on console

Note: The above program should be done using Stack

Output:
The output should like this

Enter a String: Welcome To Coal Lab

Reversed String is: baL loaC oT emocleW

UMT,Lahore Page 53
DS Department Computer Organization & Assembly language

LAB 10

Unconditional & Conditional Jumps

In this Lab you will learn:

⮚ Unconditional jump instruction


⮚ Conditional jump instruction
⮚ Branching structure –
⮚ IF-THEN
⮚ IF –THEN_ELSE
⮚ CMP Instruction

UMT,Lahore Page 54
DS Department Computer Organization & Assembly language

Unconditional Jump

The basic instruction that transfers control to another point in the program is JMP.

The basic syntax of JMP instruction:

JMP label

Conditional Jump

If the condition for the jump is the true ,the next instruction to be executed is the one at
destination label ,which may precede or follow the jump itself.

JNZ is an example of conditional jump instruction

JXXX Destination label

The CMP Instruction

The jump condition is often by CMP instruction .it has the form

CMP destination, source

The instruction compares destination and source by computing contents minus source contents.
The result is not stored, but the flags are affected.

Branching Structure

IF-THEN

The IF-THEN structure may be expressed in pseudo code as follows:

IF condition is true

Then

Execute true branch statements

END-IF

IF –THEN-ELSE

The IF-THEN-ELSE structure may be expressed in pseudo code as follows:

IF condition is true

Then

UMT,Lahore Page 55
DS Department Computer Organization & Assembly language

Execute true branch statements

ELSE

Execute false branch statements.

END-IF

● For unconditional jumps, just use JMP


● For conditional jumps, consult the following table

UMT,Lahore Page 56
DS Department Computer Organization & Assembly language

Lab Task

​Task#1
1. Prompt a user to enter a string of numbers
2. Using conditional and unconditional jumps Find the Minimum number in an array
3. Display the result on console

Output :

Output should be as follows:

Enter a string: 45672

Minimum number is: 2

Task#2

1. Input two characters from user one by one


2. Using conditions check if 1st character is greater, smaller or equal to 2nd character
3. Output the result on console

Note:

You may use these conditional jumps JE(jump equal), JG(jump greater), JL(jump low)

Output:

Enter 1st character: a

Enter 2nd character: k

Output: a is smaller than k

UMT,Lahore Page 57
DS Department Computer Organization & Assembly language

LAB 11

SEARCH AND SORT ALGORITHMS

UMT,Lahore Page 58
DS Department Computer Organization & Assembly language

Linear Search Algorithm in C

Pseudo code

1. Linear Searc (A,v)


2. For i 1 to length[A]
3. Do if A[i]=v
4. Then return i
5. Return NIL

Code in C

Function findIndex(values, target)

{ for (var i = 0; i < values. Length; ++i)

{ if (values[i] == target)

{Return i; } }

Return -1;}

Task # 1:

1. Prompt a user to enter a string array of numbers


2. Prompt a user to enter a Character
3. Search out the Number in an array and return index no if number is found Using Linear
search Algorithm
4. Display the Index No.

Output:

Input a String: 52654

User enter value: 6

Number is 6 and index no is 3

UMT,Lahore Page 59
DS Department Computer Organization & Assembly language

Bubble Sort Algorithm

Pseudo code

func bubblesort( var a as array )

For i from 1 to N

For j from 0 to N - 1

If a[j] > a[j + 1]

swap ( a[j], a[j + 1] )

end func

Code in C

void bubblesort( int * a , int n )


{ int temp; //for swapping
for ( int i = 0 ; i < n - 2 ; i++)
{ for (int j = 0 ; j < n - 1 ; j++)
{ if ( a[j] > a[j + 1] )
{temp = a[j];
a[j]=a[j + 1];
a[j + 1] = temp;
}}}}}

Task # 2:

1. Prompt a user to enter a string array of numbers


2. Sort the array in ascending order by applying Bubble Sort Algorithm
3. Display the sorted array on console

Output:

Input a String: 52654

Sorted Array is: 24556

UMT,Lahore Page 60
DS Department Computer Organization & Assembly language

HOME ASSIGNMENT

SELCTION SORT Algorithm in C

/* a[0] to a[n-1] is the array to sort */


int i,j;
int iMin;

/* advance the position through the entire array */


/* (could do j < n-1 because single element is also min element) */
for (j = 0; j < n-1; j++) {
/* find the min element in the unsorted a[j .. n-1] */

/* assume the min is the first element */


iMin = j;
/* test against elements after j to find the smallest */
for ( i = j+1; i < n; i++) {
/* if this element is less, then it is the new minimum */
if (a[i] < a[iMin]) {
/* found new minimum; remember its index */
iMin = i;
}
}

/* iMin is the index of the minimum element. Swap it with the current position */
if ( iMin != j ) {
swap(a[j], a[iMin]);
}
}

Task # 3:

4. Prompt a user to enter a string array of numbers


5. Sort the array in ascending order by applying Selection Sort Algorithm
6. Display the sorted array on console

Output:

Input a String: 52654

Sorted Array is: 24556

UMT,Lahore Page 61
DS Department Computer Organization & Assembly language

LAB 12

Multiplication & Division

In this Lab you will learn:

⮚ Multiplication
⮚ Division

UMT,Lahore Page 62
DS Department Computer Organization & Assembly language

Arithmetic Operation :-

Pentium provides several arithmetic instructions that operate on 8, 16, 32 bit operands.
v. Multiplication MUL ,IMUL
vi. Division DIV ,IDIV

Multiplication Instructions:-

MUL Unsigned multiply

Basic format
MUL source

Syntax: mul op8


mul op16

op8: 8-bit register or memory


op16: 16-bit register or memory

Action: If operand is op8, unsigned AX = AL * op8


If operand is op16, unsigned DX::AX = AX * op16

Flags Affected: OF, SF=?, ZF=?, AF=?, PF=?, CF

IMUL Signed multiply


Basic format
IMUL Source

Syntax: imul op8


imul op16

op8: 8-bit register or memory


op16: 16-bit register or memory

Action: If operand is op8, signed AX = AL * op8


If operand is op16, signed DX::AX = AX * op16

Flags Affected: OF, SF=?, ZF=?, AF=?, PF=?, CF

AAM
ASCII adjusts for Multiplication.
The AAM instruction performs the second step. It divides the content of AL by 10.
To multiply the BCD digits in AL and BL, and put the BCD product in AX

Basic format
MUL BL

UMT,Lahore Page 63
DS Department Computer Organization & Assembly language

AAM

DIVISION instruction:-

div Unsigned divide


Syntax: div op8
div op16

op8: 8-bit register or memory


op16: 16-bit register or memory

Action: If operand is op8, unsigned AL = AX / op8 and AH = AX % op8


If operand is op16, unsigned AX = DX::AX / op16 and DX = DX::AX % op16

Flags Affected: OF=? SF=? ZF=? AF=? PF=? CF=?


Notes: Performs both division and modulus operations in one instruction.

idiv Signed divide


Syntax: idiv op8
idiv op16

op8: 8-bit register or memory


op16: 16-bit register or memory

Action: If operand is op8, signed AL = AX / op8 and AH = AX % op8


If operand is op16, signed AX = DX::AX / op16 and DX = DX::AX % op16

Flags Affected: OF=? SF=? ZF=? AF=? PF=? CF=?


Notes: Performs both division and modulus operations in one instruction.

AAD
ASCII adjusts for Division.
The instruction AAD does step 1.it multiples AH by 10, adds the product to AL then clear Ah.

Basic format

▪ AAD
▪ Div BL

▪ AAM

UMT,Lahore Page 64
DS Department Computer Organization & Assembly language

LAB TASK

​Task#1
4. Prompt user to enter a string of number
5. Using multiplication, convert this string into integer (Max. input 65536)
6. Prompt user to enter 2nd string, and convert it to integer as well
7. Add both integers using ADC instruction.
8. Using Division, convert this integer sum back to String (ASCII).
9. Print the result on console

Output:

Output should be as follows:

Enter First string: 1234

Enter Second String: 5678

Sum is: 6912

Task#2

4. Prompt Student name from user.


5. Ask for his/her grades in 5 subjects (Max. marks 100).
6. Find the average of all the marks and print the average (only integer part, no decimal part
required) on console along with the grade.
7. Grade distribution is:
100 – 90:A

89 – 80: B

79 – 70: C

Else the grade is F.

UMT,Lahore Page 65
DS Department Computer Organization & Assembly language

LAB 13

Logical operations, BIT MASKING, Shift Operations

In this lab you will learn:

▪ Logical operation
● AND instruction
● OR instruction
● XOR instruction
● Not Instruction
● Test instruction

▪ LAB TASK

UMT,Lahore Page 66
DS Department Computer Organization & Assembly language

LOGICAL OPERATIONS :-

These instructions perform the specified logical operation (logical bitwise and, or, and exclusive
or, respectively) on their operands, placing the result in the first operand location.
i. AND operation
ii. OR operation
iii. XOR operation
iv. NOT operation
v. Test operation

AND Instruction:-

Perform Bitwise logical AND operation


Basic format
AND destination, source

Destination = destination & source


Five operand combinations are possible:
And register, register
And register, immediate
And memory, immediate
And memory, register
And register memory

Especially used to clear certain bits (masking)


Xxxx xxxx AND 0000 1111 = 0000 xxxx

OR Instruction:-

Perform Bitwise logical OR operation


Basic format
OR destination, source

Destination = destination | source


Five operand combinations are possible:
OR register, register
OR register, immediate
OR memory, immediate
OR memory, register
OR register memory

Especially used to set certain bits


Xxxx xxxx OR 0000 1111 = xxxx1111
(Set the upper four bits)

UMT,Lahore Page 67
DS Department Computer Organization & Assembly language

XOR Instruction:-

Perform Bitwise logical Exclusive OR operation


Basic format
XOR destination, source

Destination = destination ^ source


Five operand combinations are possible:
XOR register, register
XOR register, immediate
XOR memory, immediate
XOR memory, register
XOR register memory

The XOR instruction can be used to complement specific destination bits while preserving the
others.
01010110 XOR 0000 1111 = 01011001

AND, OR, XOR operations are


Effects on Flag
SF, ZF, PF reflect the result
AF is Undefined
CF, OF =0

NOT Instruction:-

Perform the one’s Complement operations on the destination


Basic format
NOT destination

This is not effect on status flag

TEST Instruction:

The test instruction performs an Operation of the destination with the source but does not change
the destination contents.
The purpose of the test instruction is to set the status flags.
Basics format
Test destination, source

Examining Bits
The test instruction can be used to examine individual bits in an operand

UMT,Lahore Page 68
DS Department Computer Organization & Assembly language

Lab Tasks

Task # 1:

1. Prompt a user to enter 1st character input


2. Prompt a user to enter 2nd character input
3. Perform the following logic operations in individual tasks:
1. AND, OR, ,XOR,NOT,NEG
4. By Using Test instruction and Switch Statement, check out which
particular bit is set/clear.
5. Display output on console

Example:
Result Output: 10100010
Display on console

7th bit is set


6th bit is clear
5th bit is set
4th bit is clear
3rd bit is clear
2nd bit is clear
1st bit is set
0th bit is clear

Task # 2:
1. Move a 4-digit hexadecimal number to a register
2. Separate the digits by Bit Masking
3. Display them individually

Example:
Suppose we have a number 2345h
Then by AND, SHR or SHL operations, separate 2, 3, 4 and 5 and then display the
result as
2
3
4
5

UMT,Lahore Page 69
DS Department Computer Organization & Assembly language

LAB 14

Shift and Rotate operations

In this lab you will learn

o Shift operations
o SHR instruction
o SHL instruction
o SAL instruction
o SAR Instruction

o Rotate operation

o ROR instruction
o ROL instruction
o RCL instruction
o RCR instruction

o LAB TASK

UMT,Lahore Page 70
DS Department Computer Organization & Assembly language

Shift Instruction Shift and rotate instructions shift the bits in the destination operand by one or
more positions either to the left or right

The instructions have two formats

OPCODE destination, 1

OPCODE destination, CL

The first shifts by one position, the second shifts by N positions, where CL contains N(CL is
)the only register which can be used

Effect on flags

SF, PF, ZF reflect the result

AF is undefined

CF = last bit shifted out

OF = 1 if result changes sign on last shift

Left Shift Instructions

The SHL (shift left) instruction shifts the bits in the destination to the left

Zeros are shifted into the rightmost bit positions and the last bit shifted out goes into CF

SHL Al, 4

Right Shift Instructions

The SHR (shift right) instruction shifts the bits in the destination to the right

Zeros are shifted into the leftmost bit positions and the last bit shifted out goes into CF

SHR AL, 4

The SAL instruction

The SHL instruction can be used to multiply an operand by powers of 2

To emphasize the arithmetic nature of the operation, the SAL (shift arithmetic left) is used in
instances where multiplication is intended

Both instructions generate the same machine code

The SAR instruction

UMT,Lahore Page 71
DS Department Computer Organization & Assembly language

The SAR (shift arithmetic right) instruction can be used to divide an operand by powers of 2

SAR operates like SHR, except the MSB retains its original value

The effect on the flags is the same as for SHR

If unsigned division is desired, SHR should be used instead of SAR

Rotate Instructions

Rotate Left

The instruction ROL (rotate left) shifts bits to the left

The MSB is shifted into the rightmost bit

The CF also gets the bit shifted out of the MSB

Rotate Right

ROR (rotate right) rotates bits to the right

The rightmost bit is shifted into the MSB and also into the CF

Rotate through Carry

Rotate through Carry Left

The instruction RCL shifts bits to the left. The MSB is shifted into CF

CF is shifted into the rightmost bit

Rotate through Carry Right

RCR rotates bits to the right

The rightmost bit is shifted into CF. CF is shifted into the MSB

LAB TASK

Task # 1

1. Prompt a user to enter a 3-digit number in a string array


2. Using addressing modes, address each index and convert the number into its
binary
3. Save the binary conversions of 3-digits in an array
4. Add 0’s and 1’s in this new array
5. Output the result on console

UMT,Lahore Page 72
DS Department Computer Organization & Assembly language

Note

To convert a number to its binary, you will have to do Bit Masking as done earlier i.e.
.AND, OR, SHR (shift right and SHL (shift left) operations

The above program should be done using LOOP

Output

The output should be as follow

Enter a 3-Digit Number: 987

The Binary Sum is: 6

As binary of 9 = 1001, 8 = 1000, 7 = 0111 and its sum is 6

Task # 2

Prompt a user to enter any character either alphabet or special character

Calculate its ASCII code from its hexadecimal value

Print the ASCII code with a proper output message

Output

The output should be as follow

Enter any Character

Character ASCII Code is

41h=01000001

Task #3

Verify the following instructions by executing them with DEBUG under the MS- DOS
.environment
Examine and modify the contents of the 8086’s internal register, and dedicated parts of the
memory.
Assemble instructions into memory of the PC system; TRACE each instruction to determine the
operation it performs

Operations

UMT,Lahore Page 73
DS Department Computer Organization & Assembly language

SHR, SHL, SAL, SAR, ROR, ROL, RCL, RCR

Instructions

MOV AL, 11110000


ROR Al, 1
MOV DL, 3Fh
ROR DL, 1
ROR DL, 1
ROR DL, 1
ROR DL, 1
ROL DL, 4
CLC
MOV BL, 88h
RCL BL, 1
RCL BL, 1
CLC

MOV AL, 11000110


SAR Al, 1
MOV DX, 913Fh
RCR DL, 2
RCR DL, 1
RCR DL, 2
RCR DL, 1
CLC
MOV BX, FF88h
SAR BL, 1
SAR BX, 3
SAL BX,2

UMT,Lahore Page 74
DS Department Computer Organization & Assembly language

LAB 15

Procedures And Recursions

In this lab you will learn:

▪ Procedure Declaration
▪ The CALL Instruction
▪ Executing a CALL
▪ The RET instruction
▪ Recursion
▪ LAB TASK

UMT,Lahore Page 75
DS Department Computer Organization & Assembly language

Procedure Declaration

● The syntax of procedure declaration is the following:

PROC name type


; body of procedure
ret
name endp

● type can be NEAR (in same segment) or FAR (in a different segment) -- if omitted,
NEAR is assumed

The CALL Instruction

● CALL invokes a procedure


● CALL has two forms, direct

Call name
Where name is the name of a procedure, and indirect
Call address_expression (not generally recommended)
Where address_expression specifies a register or memory location containing the
address of a procedure
Executing a CALL

● The return address to the calling program (the current value of the IP) is saved on the
stack
● IP get the offset address of the first instruction of the procedure (this transfers control to
the procedure)
● FAR procedures must process CS:IP instead of just IP

The RET instruction

● To return from a procedure, the instruction

ret pop_value
is executed

● The integer argument pop_value is optional


● ret causes the stack to be popped into IP

PROC and ENDP are compiler directives, so they are not assembled into any real machine code.
Compiler just remembers the address of the procedure.

.CALL instruction is used to call a procedure

UMT,Lahore Page 76
DS Department Computer Organization & Assembly language

Here is an example:

ORG 100h

CALL m1

MOV AX, 2

RET ; return to operating system.

m1 PROC
MOV BX, 5
RET ; return to caller.
m1 ENDP

END

Recursion

Recursion occurs when a procedure calls itself. The following, for example, is a recursive
procedure:
Recursive proc
call Recursive
ret
Recursive endp

UMT,Lahore Page 77
DS Department Computer Organization & Assembly language

Lab Task

Task # 1:

Implement the given function using Procedures

a. Parameter passing through Registers


b. Parameter passing through Stack

1. Clrscr ( )
2. Getch ( )
3. Putch ( )
4. Gets( )
5. Puts( )
6. Gotoxy ( )
7. Delay ( )
8. A to I ( )
9. I to A ( )

Task # 1:

1. Input a number from a user


2. Find its factorial recursively
3. Print the result’s hex value on console using bit masking

Example:

Enter a number: 4

Factorial value in hex is : 18h

Task # 2:

1. Input the size of Fibonacci series from user


2. Find the Fibonacci series up to that size recursively
3. Print all the hex values on console using bit masking

UMT,Lahore Page 78
DS Department Computer Organization & Assembly language

Example:

Enter the size: 8

Fibonacci series is: 1, 1, 2, 3, 5, 8, D, 15h

Sequential Search Algorithm

Sequential_ Search (value, list)


if the list is empty, return -1;
Else
if the first item of the list has the desired value, return its location;
Else return Sequentail_Search(value, remainder of the list)

Task # 1:

5. Prompt a user to enter a string array of numbers


6. Prompt a user to enter a Character
7. Search out the Number in an array and return index no if number is found Using
Sequential search Algorithm recursively.
8. Display the Index No.

Output:

Input a String: 52654

User enter value: 6

Number is 6 and index no is 3

Binary Search Algorithm

int BinarySearch (A, key, low, high) {


if (low > high) return -1;
int mid=(low+high)/2;
if (key == A[mid]) return mid;

UMT,Lahore Page 79
DS Department Computer Organization & Assembly language

if (key > A[mid])


Return BinarySearch(A, key, mid+1, high);
Else return BinarySearch(A, key, low, mid-1);
}

Task # 2:

1. Prompt a user to enter a string sorted array of numbers


2. Prompt a user to enter a Character
3. Search out the Number in an array and return index no if number is found Using Binary
search Algorithm recursively.
4. Display the Index No.

Output:

Input a String: 5 6 7 9 10 12 13 14 17

User enter value: 9

Number is 9 and index no is 4

UMT,Lahore Page 80
DS Department Computer Organization & Assembly language

Lab 18

THE string instructions

In this lab you will learn

⮚ Moving a String
⮚ Store String
⮚ Load String
⮚ Scan String
⮚ Compare String
⮚ Rep string
⮚ Lab Task

String Instructions

String in assembly language is just a sequentially stored bytes or words.


There is a very strong set of string instructions in 8086.
By using these string instructions, the size of the program is considerably reduced

UMT,Lahore Page 81
DS Department Computer Organization & Assembly language

The Directional Flag

CLD and STD


To make DF= 0, use the CLD instruction
To make DF=1, use the STD instruction

MOVS (MOVE String) instruction

● It causes moving of bytes or words from one string to another.

● In this instruction, the source string is in the Data Segment and destination string is in
Extra Segment.

● SI and DI store the offset value

REP (Repeat):

● This is an instruction prefix.

● It causes the repetition of the instruction until CX becomes zero.

● REP MOVSB STR1, STR2

● It copies byte by byte contents.

● REP repeats the operation MOVSB until CX becomes.

● REPE repeats while Equal.

● REPZ repeats while Zero.

CMPS (CoMPare Strings) Instruction

● CMPS compares two strings (of equal size), say String1 and String2, a byte or word at a
time.

● String values remain unaffected. Only flags affected.

● Basically it performs the subtraction DS:[SI]-ES:[DI]

● CMPSB for comparing Strings Byte at a time. CMPSW for comparing Strings Word at a
time. CMPSB and CMPSW are more common than CMPS

UMT,Lahore Page 82
DS Department Computer Organization & Assembly language

STOS (STOre String) instruction

● STOS is used for creating a string in memory a byte or word at a time. AL/AX contents
copied to memory pointed by ES:[DI].

● It does not affect any flag.

● STOSB is used for storing string bytes at a time.


● STOSW is used for storing string words at a time.

LODS (LOaD String) instruction

● LODS is used for processing a string in memory a byte or word at a time.

● It copies the contents of memory pointed by DS:[SI] into AL or AX.

● It does not affect any flag.

● LODSB is used for loading string bytes at a time.

● LODSW is used for loading string words at a time.

SCAS (SCAn String) instruction

● SCAS is used for scanning a string in memory for a particular byte or word.

● It compares the contents of byte in AL or word in AX with byte or word at memory


pointed by ES:[DI].

● SCAS performs AL/AX contents minus byte or word pointed by ES:[DI].

● Operand values are not changed. Flags are affected based on the result of subtraction.

● SCASB is used for scanning string bytes at a time. SCASW is used for scanning string
words at a time.

LAB TASK

Task #1

Write an Assembly language program to perform the following operation.

● Strcpy( st1,st2)

UMT,Lahore Page 83
DS Department Computer Organization & Assembly language

● Strncpy( st1,st2,n)
● Strcat(st1,st2 )
● Strlen ( st1)
● Substr(string, start, length)
● Strrev(st1,st2 )
● Strcmp(st1,st2)
● Deleting a Word from the String
● Insert a word in the string
● Searching a word from a String
Task# 2

Write an assembly language program that reads a string and displays the first 10
characters on the next line.

Algorithm for read_Str


Chars_read=0
Read a char
While char is not carriage return DO
If char is backspace
Then char_read = char_read-1
Remove previous character from string
Else
Store char in string
Char_read = char_read +1
End_ if
read a char
End_while

Algorithm for Disp_ptr


For count times DO /* count= no .of characters to display */
Load a string character into AL
Move it to DL output character
End_For

UMT,Lahore Page 84
DS Department Computer Organization & Assembly language

Lab 19

File Handling Functions in 8086

In this lab you will learn

⮚ Create File
⮚ Open File
⮚ Close File
⮚ Read File
⮚ Write File
⮚ Delete File
⮚ Changing a File Attributes
⮚ The File Pointer
⮚ Lab Task

File Handling

File handling includes

● handling of files as a whole (creating, copying, moving, deleting of files),


● accessing the file content (reading and writing)

UMT,Lahore Page 85
DS Department Computer Organization & Assembly language

A group of INT 21H functions called the File Handle Functions

INT 21H, FUNCTION 3CH-TO CREATE FILE

● Input:
● AH = 3Ch
● DS:DX = address of filename which is an ASCII string
● CL = attribute
● Output:
● If successful, AX = file handle
● Error IF CF=1, Error Code in AX(3,4,or 5)
● When a file is created or opened in a program, DOS assigns it a unique number
called the FILE HANDLE.
● This number is used to identify the file.

INT 21H, FUNCTION 3DH-TO OPEN AN EXISTING FILE

● Input:
● AH = 3Dh
● DS:DX = address of filename which is an ASCII string
● AL=Access Mode
● Mode = 0 means open for reading
o 1 means open for writing
o 2 means open for both
● Output:
● If successful, AX = file handle
● Error IF CF=1, Error Code in AX(2,4, 5,12)

INT 21H, FUNCTION 3EH-TO CLOSE A FILE

UMT,Lahore Page 86
DS Department Computer Organization & Assembly language

● Input:
● AH= 3EH
● BX = File Name
● Output:
● Error IF CF=1, Error Code in AX(6)

INT 21H, FUNCTION 40H-TO WRITE FILE

● Input:
● AH =4OH
● BX =File Handle
● CX =No Of Bytes To Write
● DS:DX =Segment: Offset Of Buffer
● Output:
● If successful then
● AX =Bytes Transferred. If AX<CX, error (Full Disk)
● Error IF CF=1, Error Code in AX(5,6)

INT 21H, FUNCTION 3Fh-TO READ FILE

● Input:
● AH = 3Fh
● BX = File Handle
● CX = Number Of Bytes To Read
● DS:DX = Memory Buffer Address
● Output:
● AX = Count Of Bytes Actually Read .
● If AX=0 or AX<CX, end of File Encounter.
● Error IF CF=1, Error Code in AX(5,6)

The File Pointer

The file pointer is used to locate a position in a file. When the file is opened, the file pointer is
positioned at the beginning of the file. After a read operation, the file pointers indicate the next
bytes to read; after writing a new file, the file pointer is at EOF (end of file).

UMT,Lahore Page 87
DS Department Computer Organization & Assembly language

INT 21H, FUNCTION 42h-TO MOVE FILE POINTER

● Input :
● AH= 42h
● Al= movement code:
● 0 means move relative to beginning of file
● 1 means move relative to the current file pointer location
● 2 means move relative to end of file
● BX = File Handle
● CX: DX = number of bytes to move (signed).
● Output:
● DX:AX = new pointer location in bytes from the beginning of the file
● If CF = 1 , error Code in AX (1 , 6).

INT 21H, FUNCTION 43h-TO GET /CHANGE FILE ATTRIBUTES

● Input :
● AH= 43h
● AL = 0 to get Attributes
● 1 to Change Attributes
● DX:DX = Address of File pathname as ASCIIZ String
● CX = new File Attributes (if AL=1)
● Output :
● If successful ,CX = Current file attributes (if AL=0)
● Error If CF = 1, error Code in AX (2, 3, or 5).

File Errors

There are many opportunities for error in INT 21h file Handling; DOS identifies each error by a
code number. If errors occur then CF is set and code appears in AX. The following list contains
more common file-handling errors.

HEX Error Code Meaning


1 Invalid function Number
2 File Not Found
3 Path not found
4 All available handles in use
5 Access denied

UMT,Lahore Page 88
DS Department Computer Organization & Assembly language

6 Invalid file handle


C Invalid access code
F Invalid drive specified
10 Attempt to remove current directory
12 No more files to be found

LAB TASK

Task #1

Write an Assembly language program to perform the following operation.

● fcreate()
● fopen()
● fwrite()
● fread()
● fseek( )
● fclose( )

UMT,Lahore Page 89
DS Department Computer Organization & Assembly language

LAB 20

Interrupts, interrupts hooks and tsr programs

In this lab you will learn

⮚ 8088/8086 Interrupts:
⮚ Interrupt Service Routine
⮚ Interrupt Vector Table
⮚ Differences between INT and CALL
⮚ Interrupt Mechanisms, Types, and Priority
⮚ Interrupts types
⮚ Terminate and Stay Resident Programs (TSR)
⮚ Storing/Hooks an Interrupt Vector in the Vector Table
⮚ Interrupt Get Vector
⮚ Interrupt Set Vector
⮚ TSR Sample Program
⮚ Interrupts Hooks Sample Program
⮚ Memory mapped I/O for text display sample Program
⮚ Lab Task

UMT,Lahore Page 90
DS Department Computer Organization & Assembly language

8088/8086 Interrupts:

An interrupt is an external event which informs the CPU that a device needs service

In the 8088 & 8086 there are total of 256 interrupts (or interrupt types)

INT 00

INT 01

INT FF

When an interrupt is executed, the microprocessor automatically saves the flags register (FR),
the instruction pointer (IP) and the code segment register (CS) on the stack and goes to a fixed
memory location.

Interrupt Service Routine

● For every interrupt, there must be a program associated with it.


● This program is called an Interrupt Service Routine (ISR)
● It is also called an interrupt handler

Interrupt Vector Table

● Interrupt vector table consists of 256 entries each containing 4 bytes.


● Each entry contains the offset and the segment addresses of the interrupt vector each 2
bytes long.
● Table starts at the memory address 00000H

In the interrupt Vector Table (IVT)


INT Number Physical Address Contains

INT 00 0000H IP0:CS0

INT 01 0004H IP1:CS1

INT 02 0008h IP2:CS2

UMT,Lahore Page 91
DS Department Computer Organization & Assembly language

INT FF 003FCH IP255:CS255

Examples

INT 12h (or vector 12)

The physical address 30h (4 x 12 = 48 = 30h) contains

0030h and 0031h contain IP of the ISR

0032h and 0033h contain CS of the ISR

Differences between INT and CALL

A CALL FAR instruction can jump any location within the 1 MB address range but INT nn goes
to a fixed memory location in the Interrupt Vector Table to get the address of the interrupt service
routine

A CALL FAR instruction is used by the programmer in the sequence of instruction in the
program but externally activated hardware interrupt can come at any time

A CALL FAR cannot be masked but INT nn in hardware can be blocked.

A CALL FAR saves CS:IP but INT nn saves Flags and CS:IP

At the end of the subroutine RET is used whereas for Interrupt routine IRET should be the last
statement.

Interrupt Mechanisms, Types, and Priority

INTERRUPT TYPES SHOWN WITH DECREASING PRIORITY ORDER


● Reset
● Internal interrupts and exceptions
● Software interrupt
● None mask able interrupt.
● Hardware interrupt
All the interrupts are serviced on priority basis. The higher priority interrupt is served first and an
active lower priority interrupt service is interrupted by a higher priority one. Lower priority
interrupts will have to wait until their turns come.
The section of program to which the control is passed called Interrupt-service routine (ISR)

Interrupts types

Interrupt Types 0-1Fh BIOS Interrupts


Interrupt Types 20h-3Fh DOS Interrupts
Interrupt Types 40h-7Fh Reserved

UMT,Lahore Page 92
DS Department Computer Organization & Assembly language

Interrupt Types 80h-F0h ROM Basic


Interrupt Type F1h-FFh Not Used

Terminate and Stay Resident Programs (TSR)

● Usually a non-resident program is a file, loaded from disk by DOS. Termination of such a
program is the passing control back to DOS.
● DOS frees all memory, allocated for and by this program, and stays idle to execute the
next program.
● Resident program passes control to DOS at the end of its execution, but leaves itself in
memory whole or partially.
● Such a program termination was called TSR - Terminate-and-Stay-Resident. So resident
programs are often called TSR.
● For example, TSR can watch key presses to get passwords, INT 13h sectors operations to
substitute info, INT 21h to watch and dispatch file operations and so on.
● TSR stays in memory to have some control over the processes. Usually, TSRs takes
Interrupt vectors to its code, so, when interrupt occurs, vector directs execution to TSR

Keep( ) in c

Terminate and stay resident


AH = 31h
AL = 00
DX = number of paragraphs
to reserve for the program
INT 21h

Storing/Hooks an Interrupt Vector in the Vector Table

In order to install an interrupt vector – sometimes called a hook, Stealing or Intercepts

The assembler must address absolute memory.

There are four basic steps for an Interrupts hook.

● Get Interrupt Vector


● Set Interrupt Vector
● Terminate and stay Resident
● Return Original Vector

Interrupt Get Vector

UMT,Lahore Page 93
DS Department Computer Organization & Assembly language

Getvect( )
Data part
Oldint dd(?)

Code part
MOV AX,0
MOV ES,AX
MOV AX,ES:[int # *4]
MOV word ptr oldint , AX
MOV Ax , Es:[int # *4+2]
MOV word ptr oldint[2], AX

Interrupt Set Vector

Setvect( )
Data part
Oldint dd(?)

Code part
MOV AX , offset my proc
MOV ES:[int # *4], AX
MOV Es:[int # *4+2],CS

Return Original Vector

Jmp dword ptr CS:oldint


OR
Pushf
Call dword ptr cs:oldint
iret

UMT,Lahore Page 94
DS Department Computer Organization & Assembly language

TSR Sample Program

.model tiny
Code_seg segment ‘Code’
Main proc far
.stratup
Jmp start
St1 db “this is int 65h”,13,10,’$’
Oldint dd (?)
Start:
Mov AX,0
Mov ES,AX
Mov AX,ES:[ 65h *4]
Mov word ptr cs: oldint , AX
Mov Ax , Es:[ 65h *4+2]
Mov word ptr cs:oldint[2], AX

Mov AX , offset my proc


Mov ES:[ 65h*4], AX
Mov Es:[65 h*4+2],CS

Mov ah,31h
Mov dx,500
Int 21h
Main endp
Myproc proc
Push ax
Push ds
Push dx

Mov ax,cs
Mov ds,ax
Mov ah,9
Mov dx,offset st1
Int 21h
Pop dx
Pop ds
Pop ax
Iret
Proc endp
Code_seg ends
End

UMT,Lahore Page 95
DS Department Computer Organization & Assembly language

Interrupts Hooks Sample Program

.model tiny
Code_seg segment ‘Code’
Main proc far
.stratup
Jmp start
St1 db “this is int 8h”,13,10,’$’
Oldint dd (?)
Start:
Mov AX,0
Mov ES,AX
Mov AX,ES:[ 8h *4]
Mov word ptr cs: oldint , AX
Mov Ax , Es:[ 8h *4+2]
Mov word ptr cs:oldint[2], AX

Mov AX , offset my proc


Mov ES:[8h *4], AX
Mov Es:[8h*4+2],CS

Mov ah,31h
Mov dx,500
Int 21h
Main endp
Myproc proc
Push ax
Push ds
Push dx

Mov ax,cs
Mov ds,ax
Mov ah,9
Mov dx,offset st1
Int 21h
Pop dx
Pop ds
Pop ax

Jmp dword ptr cs:oldint

Proc endp
Code_seg ends
end

UMT,Lahore Page 96
DS Department Computer Organization & Assembly language

Memory mapped I/O for text display sample Program

MOV AX,0B800h
MOV ES , AX
MOV DI,0
MOV word ptr ES:[DI],’U’
MOV word ptr ES:[DI],07h
MOV word ptr ES:[DI],’C’
MOV word ptr ES:[DI],70h
MOV word ptr ES:[DI],’P’
MOV word ptr ES:[DI],07h

LAB TASK

Task #1

Write a Program that intercepts keyboard interrupts. Your TSR program should call the
keyboard int9h thrice each time a key is pressed.

Task# 2

Write a TSR Program that intercepts INT 9h. Your program should convert any
occurrence of ‘1’ on screen into ‘9’ each time a key is pressed.

Task # 3

Write a TSR Program that intercepts INT 8h.Your TSR program should Display your
name with the background each time when timer interrupt is invoked.

UMT,Lahore Page 97

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy