0% found this document useful (0 votes)
74 views

cs401 Important

This document provides instructions and examples for creating assembly language programs in NASM to add three numbers. It explains how to install NASM, create and save an .asm file, compile it to a .com file using nasm, and debug the program using AFD. It also defines important assembly language concepts like registers, segments, flags, and addressing modes through examples that add three numbers stored in memory using different variable types and addressing.

Uploaded by

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

cs401 Important

This document provides instructions and examples for creating assembly language programs in NASM to add three numbers. It explains how to install NASM, create and save an .asm file, compile it to a .com file using nasm, and debug the program using AFD. It also defines important assembly language concepts like registers, segments, flags, and addressing modes through examples that add three numbers stored in memory using different variable types and addressing.

Uploaded by

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

CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.

2
File Version Update:
This version of file contains:
 How to create your first program in NASM.
 AFD Register Names
 All Example with explanation for the Hand Book
 FAQ updated version.(These must be read once because some very basic definition
and question are being answered)
 FAQ updated version.(These must be read once because some very basic terms are
being explained which you even might not found in the book)
Note: The file is best viewed in WEB LAYOUT View

Firstly Install the NASM , & AFD in hard Drive (Just Copy and Paste)Let us just say in D
Drive.
Open windows RUN box and Type cmd.
Command Prompt will open. Open D: Drive and then go to NASM folder by typing CD
NASM. CD=Change Directory
Type Edit and Edit Menu of Command Prompt will apper. Write your Assembly Language
Code.
Press Alt to open File Menu. Select Save option and provide a suitable name to the file.
And Finally save the file with the extension “.asm” (For assembly Language Files).
Now we have to convert this .asm file into .com , and this will be performed by the nasm.
For this operation, type this command.
>nasm (input_file_name).asm –o (output_name).com –l (output_name).lst
Remember “()” are for just reference .do not add them to the file name.if have file name
ex01.asm then use (file_name)=ex01.asm do not type this (file_name)=(ex01).asm
In case of successful conversion , no error message will appear. But if there is some error
message, please recheck your code by typing this code in command prompt.
Edit (input_file_name).asm (A Blue window will appear where you can examine your
code)
Now you have compilled your program ,move to next step which we will launch the
program in ADF (Advance Full Screen Debugger) where we will execute each statement of
our code and will check different changing values of different registers, and Data values
in data windows. A snapshot of the AFD is given Below.

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2

Lest us discuss some important things (Terminology) for correct code writing.
Try to remember this,

Offset
OpCode =Operation Code Just this one number tells it that it has to add, where its
operands are, and where to store the result. This number is called the opcode. The
opcode BB is for moving a constant into the BX register,
AX=Accumulator Register (
BX= Base Register (
CX= Counter Register (as there are certain instructions that work with an automatic
count)
DX = Destination Register.
-------------------------------------------------
SI= Source Index These are the index registers of the Intel architecture which hold
address of data and used in memory access.
DI= Destination Index These are the index registers of the Intel architecture which hold
address of data and used in memory access.
SP = Stack Pointer It is a memory pointer and is used indirectly by a set of instructions.
BP = Base Pointer
-------------------------------------------------
CS= Code Segment
DS= Data Segment
ES= Extra Segment
SS=Stack Segment
--------------------------------------------------
IP = Instruction Pointer This is the special register containing the address of the next
instruction to be executed.
HS= No Found
FS= Not Found

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
-------------------------------------------------
Flag Registers
C Flag =Carry Flag
P Flag = Parity Flag
A Flag = Auxiliary Carry
Z Flag = Zero Flag
S Flag = Sign Flag
T Flag = Trap Flag
I Flag = Interrupt Flag
D Flag = Direction Flag
O Flag = Over Flow Flag

Program No.01 Example 1.1


; a program to add three numbers using registers
[org 0x0100]
mov ax, 5 ; load first number in ax
mov bx, 10 ; load second number in bx
add ax, bx ; accumulate sum in ax
mov bx, 15 ; load third number in bx
add ax, bx ; accumulate sum in ax
mov ax, 0x4c00 ; terminate program
int 0x21
001 To start a comment a semicolon is used and the assembler ignores everything else
on the same line. Comments must be extensively used in assembly language programs to
make them readable. 002 Leave the org directive for now as it will be discussed later.
003 The constant 5 is loaded in one register AX.004 The constant 10 is loaded in another
register BX.005 Register BX is added to register AX and the result is stored in register
AX. Register AX should contain 15 by now.006 The constant 15 is loaded in the register
BX.
007 Register BX is again added to register AX now producing 15+15=30
in the AX register. So the program has computed 5+10+15=30.008 Vertical spacing must
also be used extensively in assembly language programs to separate logical blocks of
code.
009-010 The ending lines are related more to the operating system than to assembly
language programming. It is a way to inform DOS that our program has terminated so it
can display its command prompt again. The computer may reboot or behave improperly
if thistermination is not present.
=========================================================

Program No.02 Example 2.1

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
; a program to add three numbers using memory variables
[org 0x0100]
mov ax, [num1] ; load first number in ax
mov bx, [num2] ; load second number in bx
add ax, bx ; accumulate sum in ax
mov bx, [num3] ; load third number in bx
add ax, bx ; accumulate sum in ax
mov [num4], ax ; store sum in num4
mov ax, 0x4c00 ; terminate program
int 0x21
num1: dw 5
num2: dw 10
num3: dw 15
num4: dw 0
002 Originate our program at 0100. The first executable instructions should be placed at
this offset.003 The source operand is changed from constant 5 to [num1]. The bracket is
signaling that the operand is placed in memory at address num1. The value 5 will be
loaded in ax even though we did not specified it in our program code, rather the value
will be picked from memory. The instruction should be read as “read the contents of
memory location num1 in the ax register.” The label num1 is a symbol for us but an
address for the processor while the conversion is done by the assembler. 013 The label
num1 is defined as a word and the assembler is requested to place 5 in that memory
location. The colon signals that num1 is a label and not an instruction.
================================================================

Program No.03 Example 2.2


; a program to add three numbers accessed using a single label
[org 0x0100]
mov ax, [num1] ; load first number in ax
mov bx, [num1+2] ; load second number in bx
add ax, bx ; accumulate sum in ax
mov bx, [num1+4] ; load third number in bx
add ax, bx ; accumulate sum in ax
mov [num1+6], ax ; store sum at num1+6
mov ax, 0x4c00 ; terminate program
int 0x21
num1: dw 5
dw 10
dw 15
dw 0
004 The second number is read from num1+2. Similarly the third number is read from
num1+4 and the result is accessed at num1+6. 013-016 The labels num2, num3, and
num4 are removed and the data there will be accessed with reference to num1.
==================================================================

Program No.04 Example 2.3


; a program to add three numbers accessed using a single label

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
[org 0x0100]
mov ax, [num1] ; load first number in ax
mov bx, [num1+2] ; load second number in bx
add ax, bx ; accumulate sum in ax
mov bx, [num1+4] ; load third number in bx
add ax, bx ; accumulate sum in ax
mov [num1+6], ax ; store sum at num1+6
mov ax, 0x4c00 ; terminate program
int 0x21
num1: dw 5, 10, 15, 0
013 As we do not need to place labels on individual variables we can save space and
declare all data on a single line separated by commas.This declaration will declare four
words in consecutive memory locations while the address of first one is num1.
=================================================================

Program No.05 Example 2.4


; a program to add three numbers directly in memory
[org 0x0100]
mov ax, [num1] ; load first number in ax
mov [num1+6], ax ; store first number in result
mov ax, [num1+2] ; load second number in ax
add [num1+6], ax ; add second number to result
mov ax, [num1+4] ; load third number in ax
add [num1+6], ax ; add third number to result
mov ax, 0x4c00 ; terminate program
int 0x21
num1: dw 5, 10, 15, 0
============================================================

Program No.06 Example 2.5


; a program to add three numbers using byte variables
[org 0x0100]
mov al, [num1] ; load first number in al
mov bl, [num1+1] ; load second number in bl
add al, bl ; accumulate sum in al
mov bl, [num1+2] ; load third number in bl
add al, bl ; accumulate sum in al
mov [num1+3], al ; store sum at num1+3
mov ax, 0x4c00 ; terminate program
int 0x21
num1: db 5, 10, 15, 0
003 The number is read in AL register which is a byte register since the memory location
read is also of byte size.005 The second number is now placed at num1+1 instead of
num1+2 because of byte offsets.013 To declare data db is used instead of dw so that
each data declared occupies one byte only.
===========================================================================
Program No.07 Example 2.6

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
; a program to add three numbers using indirect addressing
[org 0x100]
mov bx, num1 ; point bx to first number
mov ax, [bx] ; load first number in ax
add bx, 2 ; advance bx to second number
add ax, [bx] ; add second number to ax
add bx, 2 ; advance bx to third number
add ax, [bx] ; add third number to ax
add bx, 2 ; advance bx to result
mov [bx], ax ; store sum at num1+6
mov ax, 0x4c00 ; terminate program
int 0x21
num1: dw 5, 10, 15, 0
003 Observe that no square brackets around num1 are used this time. The address is
loaded in bx and not the contents. Value of num1 is 0005 and the address is 0117. So
BX will now contain 0117. 004 Brackets are now used around BX. In iapx88
architecture brackets can be used around BX, BP, SI, and DI only. In iapx386 more
registers are allowed. The instruction will be read as “move into ax the contents of the
memory location whose address is in bx.” Now since bx contains the address of num1 the
contents of num1 are transferred to the ax register. Without square brackets the
meaning of the instruction would have been totally different.005 This instruction is
changing the address. Since we have words not bytes, we add two to bx so that it points
to the next word in memory.BX now contains 0119 the address of the second word in
memory.This was the mechanism to change addresses that we needed.
===============================================================
Program No.08 Example 2.7
; a program to add ten numbers
[org 0x0100]
mov bx, num1 ; point bx to first number
mov cx, 10 ; load count of numbers in cx
mov ax, 0 ; initialize sum to zero
l1: add ax, [bx] ; add number to ax
add bx, 2 ; advance bx to next number
sub cx, 1 ; numbers to be added reduced
jnz l1 ; if numbers remain add next
mov [total], ax ; write back sum in memory
mov ax, 0x4c00 ; terminate program
int 0x21
num1: dw 10, 20, 30, 40, 50, 10, 20, 30, 40, 50
018 total: dw 0
006 Labels can be used on code as well. Just like data labels they remember the address
at which they are used. The assembler does not differentiate between code labels and
data labels. The programmer is responsible for using a data label as data and a code
label as code. The label l1 in this case is the address of the following instruction. 009
SUB is the counterpart to ADD with the same rules as that of the ADD instruction. 010
JNZ stands for “jump if not zero.” NZ is the condition in this instruction. So the
instruction is read as “jump to the location l1 if the zero flag is not set.” And revisiting
www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
the zero flag definition “the zero flag is set if the last mathematical or logical operation
has produced a zero in its destination.” For example “mov ax, 0” will not set the zero flag
as it is not a mathematical or logical instruction. However subtraction and addition will
set it. Also it is set even when
the destination is not a register. Now consider the subtraction immediately preceding it.
If the CX register becomes zero as a result of this subtraction the zero flag will be set and
the jump will be taken. And jump to l1, the processor needs to be told each and
everything and the destination is an important part of every jump. Just like when we as
someone to go, we mention go to this market or that house. The processor is much more
logical than us and needs the destination in every instruction that asks it to go
somewhere. The processor will load l1 in the IP register and resume execution from there.
The processor will blindly go to the label we mention even if it contains data and not
code.
The JNZ instruction is from the program control group and is a conditional jump,
meaning that if the condition NZ is true (ZF=0) it will jump to the address mentioned and
otherwise it will progress to the next instruction. It is a selection between two paths. If
the condition is true go right and otherwisego left.
====================================================================
Program No.09 Example 2.8
; a program to add ten numbers using register + offset addressing
[org 0x0100]
mov bx, 0 ; initialize array index to zero
mov cx, 10 ; load count of numbers in cx
mov ax, 0 ; initialize sum to zero
l1: add ax, [num1+bx] ; add number to ax
add bx, 2 ; advance bx to next index
sub cx, 1 ; numbers to be added reduced
jnz l1 ; if numbers remain add next
mov [total], ax ; write back sum in memory
mov ax, 0x4c00 ; terminate program
int 0x21
num1: dw 10, 20, 30, 40, 50, 10, 20, 30, 40, 50
total: dw 0
003 This time BX is initialized to zero instead of array base 007 The format of memory
access has changed. The array base is added to BX containing array index at the time of
memory access.008 As the array is of words, BX jumps in steps of two, i.e. 0, 2, 4.
Higher level languages do appropriate incrementing themselves and we always use
sequential array indexes. However in assembly language we always calculate in bytes
and therefore we need to take care of the size of one array element which in this case is
two.
==================================================================
The operation of all jumps can be seen from the following table

The CMP instruction sets the flags reflecting the relation of the destination
to the source.
=====================================================================

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
Program No.10 Example 3.1
; a program to add ten numbers without a separate counter
[org 0x0100]
mov bx, 0 ; initialize array index to zero
mov ax, 0 ; initialize sum to zero
l1: add ax, [num1+bx] ; add number to ax
add bx, 2 ; advance bx to next index
cmp bx, 20 ; are we beyond the last index
jne l1 ; if not add next number
mov [total], ax ; write back sum in memory
mov ax, 0x4c00 ; terminate program
int 0x21
num1: dw 10, 20, 30, 40, 50, 10, 20, 30, 40, 50
total: dw 0
006 The format of memory access is still base + offset.008 BX is used as the array index
as well as the counter. The offset of 11th number will be 20, so as soon as BX becomes
20 just after the 10th number has been added, the addition is stopped.009 The jump is
displayed as JNZ in the debugger even though we have written JNE in our example. This
is because it is a renamed jump with the same opcode as JNZ and the debugger has no
way of knowing the mnemonic that we used after looking just at the opcode. Also every
code and data reference that we used till now is seen in the opcode as well. However for
the jump instruction we see an operand of F2 in the opcode and not 0116. This will be
discussed in detail with unconditional jumps. It is actually a short relative jump and the
operand is stored in the form of positive or negative offset from this instruction.
=================================================================
Program No.11 Example 3.2
; a program to add ten numbers without a separate counter
[org 0x0100]
jmp start ; unconditionally jump over data
num1: dw 10, 20, 30, 40, 50, 10, 20, 30, 40, 50
total: dw 0
start: mov bx, 0 ; initialize array index to zero
mov ax, 0 ; initialize sum to zero
l1: add ax, [num1+bx] ; add number to ax
add bx, 2 ; advance bx to next index
cmp bx, 20 ; are we beyond the last index
jne l1 ; if not add next number
mov [total], ax ; write back sum in memory
mov ax, 0x4c00 ; terminate program
int 0x21
003 JMP jumps over the data declarations to the start label and execution resumes from
there.
=================================================================
Program No.12 Example 3.3
; sorting a list of ten numbers using bubble sort
[org 0x0100]
jmp start

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
data: dw 60, 55, 45, 50, 40, 35, 25, 30, 10, 0
swap: db 0
start: mov bx, 0 ; initialize array index to zero
mov byte [swap], 0 ; rest swap flag to no swaps
loop1: mov ax, [data+bx] ; load number in ax
cmp ax, [data+bx+2] ; compare with next number
jbe noswap ; no swap if already in order
mov dx, [data+bx+2] ; load second element in dx
mov [data+bx+2], ax ; store first number in second
mov [data+bx], dx ; store second number in first
mov byte [swap], 1 ; flag that a swap has been done
noswap: add bx, 2 ; advance bx to next index
cmp bx, 18 ; are we at last index
jne loop1 ; if not compare next two
cmp byte [swap], 1 ; check if a swap has been done
je bsort ; if yes make another pass
mov ax, 0x4c00 ; terminate program
int 0x21
003 The jump instruction is placed to skip over data. 006 The swap flag can be stored in
a register but as an example it is stored in memory and also to extend the concept at a
later stage.011-012 One element is read in AX and it is compared with the next element
because memory to memory comparisons are not allowed. 013 If the JBE is changed to
JB, not only the unnecessary swap on equal will be performed, there will be a major
algorithmic flaw due to a logical error as in the case of equal elements the algorithm will
never stop. JBE won’t swap in the case of equal elements. 015-017 The swap is done
using DX and AX registers in such a way that the values are crossed. The code uses the
information that one of the elements is already in the AX register. 021 This time BX is
compared with 18 instead of 20 even though the number of elements is same. This is
because we pick an element and compare it with the next element. When we pick the 9th
element we compare it with the next element and this is the last comparison, since if we
pick the 10th element we will compare it with the 11th element and there is no 11th
element in our case. 024-025 If a swap is done we repeat the whole process for possible
more swaps.
===============================================================
Program No.13 Example 4.1
; 4bit multiplication algorithm
[org 0x100]
jmp start
multiplicand: db 13 ; 4bit multiplicand (8bit space)
multiplier: db 5 ; 4bit multiplier
result: db 0 ; 8bit result
start: mov cl, 4 ; initialize bit count to four
mov bl, [multiplicand] ; load multiplicand in bl
mov dl, [multiplier] ; load multiplier in dl
checkbit: shr dl, 1 ; move right most bit in carry
jnc skip ; skip addition if bit is zero
add [result], bl ; accumulate result
www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
skip: shl bl, 1 ; shift multiplicand left
dec cl ; decrement bit count
jnz checkbit ; repeat if bits left
mov ax, 0x4c00 ; terminate program
int 0x21
The numbers to be multiplied are constants for now. The multiplication is four bit so the
answer is stored in an 8bit register. If the operands were 8bit the answer would be 16bit
and if the operands were 16bit the answer would be 32bit. Since eight bits can fit in a
byte we have used 4bit multiplication as our first example. Since addition by zero means
nothing we skip the addition step if the rightmost bit of the multiplier is zero. If the jump
is not taken the shifted value of the multiplicand is added to the result.The multiplicand
is left shifted in every iteration regardless of the multiplier bit.DEC is a new instruction
but its operation should be immediately understandable with the knowledge gained till
now. It simply subtracts one from its single operand. The JNZ instruction causes the
algorithm to repeat till any bits of the multiplier are left
=================================================================
Program No.14 Example 4.2
; 16bit multiplication
[org 0x0100]
jmp start
multiplicand: dd 1300 ; 16bit multiplicand 32bit space
multiplier: dw 500 ; 16bit multiplier
result: dd 0 ; 32bit result
start: mov cl, 16 ; initialize bit count to 16
mov dx, [multiplier] ; load multiplier in dx
checkbit: shr dx, 1 ; move right most bit in carry
jnc skip ; skip addition if bit is zero
mov ax, [multiplicand]
add [result], ax ; add less significant word
mov ax, [multiplicand+2]
adc [result+2], ax ; add more significant word
skip: shl word [multiplicand], 1
rcl word [multiplicand+2], 1 ; shift multiplicand left
dec cl ; decrement bit count
jnz checkbit ; repeat if bits left
mov ax, 0x4c00 ; terminate program
int 0x21
05-07
10
15-18
20-21
The multiplicand and the multiplier are stored in 32bit space while the multiplier is
stored as a word.The multiplier is loaded in DX where it will be shifted bit by bit. It can
be directly shifted in memory as well.The multiplicand is added to the result using
extended 32bit
addition.The multiplicand is shifted left as a 32bit number using extended shifting
operation.

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
================================================================
Program No.15 Example 4.3
; 16bit multiplication using test for bit testing
[org 0x0100]
jmp start
multiplicand: dd 1300 ; 16bit multiplicand 32bit space
multiplier: dw 500 ; 16bit multiplier
result: dd 0 ; 32bit result
start: mov cl, 16 ; initialize bit count to 16
mov bx, 1 ; initialize bit mask
checkbit: test bx, [multiplier] ; move right most bit in carry
jz skip ; skip addition if bit is zero
mov ax, [multiplicand]
add [result], ax ; add less significant word
mov ax, [multiplicand+2]
adc [result+2], ax ; add more significant word
skip: shl word [multiplicand], 1
rcl word [multiplicand+2], 1 ; shift multiplicand left
shl bx, 1 ; shift mask towards next bit
dec cl ; decrement bit count
jnz checkbit ; repeat if bits left
mov ax, 0x4c00 ; terminate program
int 0x21
12
22-24
The test instruction is used for bit testing. BX holds the mask and in every next iteration
it is shifting left, as our concerned bit is now the next bit. We can do without counting in
this example. We can stop as soon as our mask in BX becomes zero. These are the small
tricks that assembly allows us to do and optimize our code as a result.
==================================================================
Program No.16 Example 5.1
; bubble sort algorithm as a subroutine
[org 0x0100]
jmp start
data: dw 60, 55, 45, 50, 40, 35, 25, 30, 10, 0
swap: db 0
bubblesort: dec cx ; last element not compared
shl cx, 1 ; turn into byte count
mainloop: mov si, 0 ; initialize array index to zero
mov byte [swap], 0 ; reset swap flag to no swaps
innerloop: mov ax, [bx+si] ; load number in ax
cmp ax, [bx+si+2] ; compare with next number
jbe noswap ; no swap if already in order
mov dx, [bx+si+2] ; load second element in dx
mov [bx+si], dx ; store first number in second
mov [bx+si+2], ax ; store second number in first
mov byte [swap], 1 ; flag that a swap has been done

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
noswap: add si, 2 ; advance si to next index
cmp si, cx ; are we at last index
jne innerloop ; if not compare next two
cmp byte [swap], 1 ; check if a swap has been done
je mainloop ; if yes make another pass
ret ; go back to where we came from
start: mov bx, data ; send start of array in bx
mov cx, 10 ; send count of elements in cx
call bubblesort ; call our subroutine
mov ax, 0x4c00 ; terminate program
int 0x21
08-09
The routine has received the count of elements in CX. Since it makes one less
comparison than the number of elements it decrements it. Then it multiplies it by two
since this a word array and each element takes two bytes. Left shifting has been used to
multiply by two.
Base+index+offset addressing has been used. BX holds the start of array, SI the offset
into it and an offset of 2 when the next element is to be read. BX can be directly changed
but then a separate counter would be needed, as SI is directly compared with CX in our
case.
The code starting from the start label is our main program analogous to the main in the
C language. BX and CX hold our parameters for the bubblesort subroutine and the CALL
is made to invoke the subroutine.
==============================================================
Program No.17 Example 5.2
; bubble sort subroutine called twice
[org 0x0100]
jmp start
data: dw 60, 55, 45, 50, 40, 35, 25, 30, 10, 0
data2: dw 328, 329, 898, 8923, 8293, 2345, 10, 877, 355, 98
dw 888, 533, 2000, 1020, 30, 200, 761, 167, 90, 5
swap: db 0
bubblesort: dec cx ; last element not compared
shl cx, 1 ; turn into byte count
mainloop: mov si, 0 ; initialize array index to zero
mov byte [swap], 0 ; reset swap flag to no swaps
innerloop: mov ax, [bx+si] ; load number in ax
cmp ax, [bx+si+2] ; compare with next number
jbe noswap ; no swap if already in order
mov dx, [bx+si+2] ; load second element in dx
mov [bx+si], dx ; store first number in second
mov [bx+si+2], ax ; store second number in first
mov byte [swap], 1 ; flag that a swap has been done
noswap: add si, 2 ; advance si to next index
cmp si, cx ; are we at last index
jne innerloop ; if not compare next two
cmp byte [swap], 1 ; check if a swap has been done

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
je mainloop ; if yes make another pass
ret ; go back to where we came from
start: mov bx, data ; send start of array in bx
mov cx, 10 ; send count of elements in cx
call bubblesort ; call our subroutine
mov bx, data2 ; send start of array in bx
mov cx, 20 ; send count of elements in cx
call bubblesort ; call our subroutine again
mov ax, 0x4c00 ; terminate program
int 0x21
05-07
34-40
There are two different data arrays declared. One of 10 elements and the other of 20
elements. The second array is declared on two lines,where the second line is continuation
of the first. No additional label is needed since they are situated consecutively in
memory.
The other change is in the main where the bubblesort subroutine is called twice, once on
the first array and once on the second.
========================================================================
Program No.18 Example 5.3
; bubble sort subroutine using swap subroutine
[org 0x0100]
jmp start
data: dw 60, 55, 45, 50, 40, 35, 25, 30, 10, 0
data2: dw 328, 329, 898, 8923, 8293, 2345, 10, 877, 355, 98
dw 888, 533, 2000, 1020, 30, 200, 761, 167, 90, 5
swapflag: db 0
swap: mov ax, [bx+si] ; load first number in ax
xchg ax, [bx+si+2] ; exchange with second number
mov [bx+si], ax ; store second number in first
ret ; go back to where we came from
bubblesort: dec cx ; last element not compared
shl cx, 1 ; turn into byte count
mainloop: mov si, 0 ; initialize array index to zero
mov byte [swapflag], 0 ; reset swap flag to no swaps
innerloop: mov ax, [bx+si] ; load number in ax
cmp ax, [bx+si+2] ; compare with next number
jbe noswap ; no swap if already in order
call swap ; swaps two elements
mov byte [swapflag], 1 ; flag that a swap has been done
noswap: add si, 2 ; advance si to next index
cmp si, cx ; are we at last index
jne innerloop ; if not compare next two
cmp byte [swapflag], 1 ; check if a swap has been done
je mainloop ; if yes make another pass
ret ; go back to where we came from
start: mov bx, data ; send start of array in bx

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
mov cx, 10 ; send count of elements in cx
call bubblesort ; call our subroutine
mov bx, data2 ; send start of array in bx
mov cx, 20 ; send count of elements in cx
call bubblesort ; call our subroutine again
mov ax, 0x4c00 ; terminate program
int 0x21
A new instruction XCHG has been introduced. The instruction swaps its source and its
destination operands however at most one of the operands could be in memory, so the
other has to be loaded in a register. The instruction has reduced the code size by one
instruction. The RET at the end of swap makes it a subroutine.
===============================================================,
Program No.19 Example 5.4
; bubble sort and swap subroutines saving and restoring registers
[org 0x0100]
jmp start
data: dw 60, 55, 45, 50, 40, 35, 25, 30, 10, 0
data2: dw 328, 329, 898, 8923, 8293, 2345, 10, 877, 355, 98
dw 888, 533, 2000, 1020, 30, 200, 761, 167, 90, 5
swapflag: db 0
swap: push ax ; save old value of ax
mov ax, [bx+si] ; load first number in ax
xchg ax, [bx+si+2] ; exchange with second number
mov [bx+si], ax ; store second number in first
pop ax ; restore old value of ax
ret ; go back to where we came from
bubblesort: push ax ; save old value of ax
push cx ; save old value of cx
push si ; save old value of si
dec cx ; last element not compared
shl cx, 1 ; turn into byte count
mainloop: mov si, 0 ; initialize array index to zero
mov byte [swapflag], 0 ; reset swap flag to no swaps
innerloop: mov ax, [bx+si] ; load number in ax
cmp ax, [bx+si+2] ; compare with next number
jbe noswap ; no swap if already in order
call swap ; swaps two elements
mov byte [swapflag], 1 ; flag that a swap has been done
noswap: add si, 2 ; advance si to next index
cmp si, cx ; are we at last index
jne innerloop ; if not compare next two
cmp byte [swapflag], 1 ; check if a swap has been done
je mainloop ; if yes make another pass
pop si ; restore old value of si
pop cx ; restore old value of cx
pop ax ; restore old value of ax
ret ; go back to where we came from

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
start: mov bx, data ; send start of array in bx
mov cx, 10 ; send count of elements in cx
call bubblesort ; call our subroutine
mov bx, data2 ; send start of array in bx
mov cx, 20 ; send count of elements in cx
call bubblesort ; call our subroutine again
mov ax, 0x4c00 ; terminate program
int 0x21
19-21 When multiple registers are pushed, order is very important. If AX,CX, and SI are
pushed in this order, they must be popped in the reverse order of SI, CX, and AX. This is
again because the stack behaves in a Last In First Out manner.
====================================================================
Program No.20 Example 5.5
; bubble sort subroutine taking parameters from stack
[org 0x0100]
jmp start
data: dw 60, 55, 45, 50, 40, 35, 25, 30, 10, 0
data2: dw 328, 329, 898, 8923, 8293, 2345, 10, 877, 355, 98
dw 888, 533, 2000, 1020, 30, 200, 761, 167, 90, 5
swapflag: db 0
bubblesort: push bp ; save old value of bp
mov bp, sp ; make bp our reference point
push ax ; save old value of ax
push bx ; save old value of bx
push cx ; save old value of cx
push si ; save old value of si
mov bx, [bp+6] ; load start of array in bx
mov cx, [bp+4] ; load count of elements in cx
dec cx ; last element not compared
shl cx, 1 ; turn into byte count
mainloop: mov si, 0 ; initialize array index to zero
mov byte [swapflag], 0 ; reset swap flag to no swaps
innerloop: mov ax, [bx+si] ; load number in ax
cmp ax, [bx+si+2] ; compare with next number
jbe noswap ; no swap if already in order
xchg ax, [bx+si+2] ; exchange ax with second number
mov [bx+si], ax ; store second number in first
mov byte [swapflag], 1 ; flag that a swap has been done
noswap: add si, 2 ; advance si to next index
cmp si, cx ; are we at last index
jne innerloop ; if not compare next two
cmp byte [swapflag], 1 ; check if a swap has been done
je mainloop ; if yes make another pass
pop si ; restore old value of si
pop cx ; restore old value of cx
pop bx ; restore old value of bx
pop ax ; restore old value of ax

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
pop bp ; restore old value of bp
ret 4 ; go back and remove two params
start: mov ax, data
push ax ; place start of array on stack
mov ax, 10
push ax ; place element count on stack
call bubblesort ; call our subroutine
mov ax, data2
push ax ; place start of array on stack
mov ax, 20
push ax ; place element count on stack
call bubblesort ; call our subroutine again
mov ax, 0x4c00 ; terminate program
int 0x21
11
45
47-50
The value of the stack pointer is captured in the base pointer. With further pushes SP
will change but BP will not and therefore we will read parameters from bp+4 and bp+6.
The form of RET that takes an argument is used causing four to be added to SP after the
return address has been popped in the instruction pointer. This will effectively discard
the parameters that are still there on the stack. We push the address of the array we
want to sort followed by the count of elements. As immediate cannot be directly pushed
in the
8088 architecture, we first load it in the AX register and then push the AX register on the
stack.
=================================================================
Program No.21 Example 5.6
; bubble sort subroutine using a local variable
[org 0x0100]
jmp start
data: dw 60, 55, 45, 50, 40, 35, 25, 30, 10, 0
data2: dw 328, 329, 898, 8923, 8293, 2345, 10, 877, 355, 98
dw 888, 533, 2000, 1020, 30, 200, 761, 167, 90, 5
bubblesort: push bp ; save old value of bp
mov bp, sp ; make bp our reference point
sub sp, 2 ; make two byte space on stack
push ax ; save old value of ax
push bx ; save old value of bx
push cx ; save old value of cx
push si ; save old value of si
mov bx, [bp+6] ; load start of array in bx
mov cx, [bp+4] ; load count of elements in cx
dec cx ; last element not compared
shl cx, 1 ; turn into byte count
mainloop: mov si, 0 ; initialize array index to zero
mov word [bp-2], 0 ; reset swap flag to no swaps

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
innerloop: mov ax, [bx+si] ; load number in ax
cmp ax, [bx+si+2] ; compare with next number
jbe noswap ; no swap if already in order
xchg ax, [bx+si+2] ; exchange ax with second number
mov [bx+si], ax ; store second number in first
mov word [bp-2], 1 ; flag that a swap has been done
noswap: add si, 2 ; advance si to next index
cmp si, cx ; are we at last index
jne innerloop ; if not compare next two
cmp word [bp-2], 1 ; check if a swap has been done
je mainloop ; if yes make another pass
pop si ; restore old value of si
pop cx ; restore old value of cx
pop bx ; restore old value of bx
pop ax ; restore old value of ax
mov sp, bp ; remove space created on stack
pop bp ; restore old value of bp
ret 4 ; go back and remove two params
start: mov ax, data
push ax ; place start of array on stack
mov ax, 10
push ax ; place element count on stack
call bubblesort ; call our subroutine
mov ax, data2
push ax ; place start of array on stack
mov ax, 20
push ax ; place element count on stack
call bubblesort ; call our subroutine again
mov ax, 0x4c00 ; terminate program
int 0x21
A word gap has been created for swap flag. This is equivalent to a dummy push. The
registers are pushed above this gap. The swapflag is accessed with [bp-2]. The
parameters are accessed in the same manner as the last examples. We are removing the
hole that we created. The hole is removed by restoring the value of SP that it had at the
time of snapshot or at the value it had before the local variable was created. This can be
replaced with “add sp, 2” however the one used in the code is preferred since it does not
require to remember how much space for local variables was allocated in the start. After
this operation SP points to the old value of BP from where we can proceed as usual.
==============================================================
Program No.22 Example 6.1
; clear the screen
[org 0x0100]
mov ax, 0xb800 ; load video base in ax
mov es, ax ; point es to video base
mov di, 0 ; point di to top left column
nextchar: mov word [es:di], 0x0720 ; clear next char on screen
add di, 2 ; move to next screen location

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
cmp di, 4000 ; has the whole screen cleared
jne nextchar ; if no clear next position
mov ax, 0x4c00 ; terminate program
int 0x21
07
08
09
The code for space is 20 while 07 is the normal attribute of low intensity white on black
with no blinking. Even to clear the screen or put a blank on a location there is a numeric
code. DI is incremented twice since each screen location corresponds to two byte in video
memory.DI is compared with 80*25*2=4000. The last word location that corresponds to
the screen is 3998.
===============================================================
Program No.23 Example 6.2
; hello world in assembly
[org 0x0100]
jmp start
message: db 'hello world' ; string to be printed
length: dw 11 ; length of the string
; subroutine to clear the screen
clrscr: push es
push ax
push di
mov ax, 0xb800
mov es, ax ; point es to video base
mov di, 0 ; point di to top left column
nextloc: mov word [es:di], 0x0720 ; clear next char on screen
add di, 2 ; move to next screen location
cmp di, 4000 ; has the whole screen cleared
jne nextloc ; if no clear next position
pop di
pop ax
pop es
ret
; subroutine to print a string at top left of screen
; takes address of string and its length as parameters
printstr: push bp
mov bp, sp
push es
push ax
push cx
push si
push di
mov ax, 0xb800
mov es, ax ; point es to video base
mov di, 0 ; point di to top left column
mov si, [bp+6] ; point si to string

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
mov cx, [bp+4] ; load length of string in cx
mov ah, 0x07 ; normal attribute fixed in al
nextchar: mov al, [si] ; load next char of string
mov [es:di], ax ; show this char on screen
add di, 2 ; move to next screen location
add si, 1 ; move to next char in string
loop nextchar ; repeat the operation cx times
pop di
pop si
pop cx
pop ax
pop es
pop bp
ret 4
start: call clrscr ; call the clrscr subroutine
mov ax, message
push ax ; push address of message
push word [length] ; push message length
call printstr ; call the printstr subroutine
mov ax, 0x4c00 ; terminate program
int 0x21
05-06
09-25
29-35
37-42
44-45
The string definition syntax discussed above is used to declare a string “hello world” of
11 bytes and the length is stored in a separate variable.The code to clear the screen from
the last example is written in the form of a subroutine. Since the subroutine had no
parameters, only modified registers are saved and restored from the stack.The standard
subroutine format with parameters received via stack and all registers saved and
restored is used.ES is initialized to point to the video memory via the AX register.Two
pointer registers are used; SI to point to the string and DI to point to the top left location
of the screen. CX is loaded with the length of the string. Normal attribute of low intensity
white on black with no blinking is loaded in the AH register.The next character from the
string is loaded into AL. Now AH holds the attribute and AL the ASCII code of the
character. This pair is written on the video memory using DI with the segment override
prefix for ES to access the video memory segment.The string pointer is incremented by
one while the video memory pointer is incremented by two since one char corresponds to
a word on the screen.The loop instruction used is equivalent to a combination of “dec cx”
and “jnz nextchar.” The loop is executed CX times.The registers pushed on the stack are
recovered in opposite order and the “ret 4” instruction removes the two parameters
placed on
the stack.Memory can be directly pushed on the stack.
================================================================
Program No.24 Example 6.3
; number printing algorithm

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
[org 0x0100]
jmp start
;;;;; COPY LINES 008-025 FROM EXAMPLE 6.2 (clrscr) ;;;;;
; subroutine to print a number at top left of screen
; takes the number to be printed as its parameter
printnum: push bp
mov bp, sp
push es
push ax
push bx
push cx
push dx
push di
mov ax, 0xb800
mov es, ax ; point es to video base
mov ax, [bp+4] ; load number in ax
mov bx, 10 ; use base 10 for division
mov cx, 0 ; initialize count of digits
nextdigit: mov dx, 0 ; zero upper half of dividend
div bx ; divide by 10
add dl, 0x30 ; convert digit into ascii value
push dx ; save ascii value on stack
inc cx ; increment count of values
cmp ax, 0 ; is the quotient zero
jnz nextdigit ; if no divide it again
mov di, 0 ; point di to top left column
nextpos: pop dx ; remove a digit from the stack
mov dh, 0x07 ; use normal attribute
mov [es:di], dx ; print char on screen
add di, 2 ; move to next screen location
loop nextpos ; repeat for all digits on stack
pop di
pop dx
pop cx
pop bx
pop ax
pop es
pop bp
ret 2
start: call clrscr ; call the clrscr subroutine
mov ax, 4529
push ax ; place number on stack
call printnum ; call the printnum subroutine
mov ax, 0x4c00 ; terminate program
int 0x21
026-033
The registers are saved as an essential practice. The only parameter received is the
number to be printed.035-039 ES is initialized to video memory. AX holds the number to
www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
be printed. BX is the desired base, and can be loaded from a parameter.CX holds the
number of digits pushed on the stack. This count is initialized to zero, incremented with
every digit pushed and is used when the digits are popped one by one.041-042 DX must
be zeroed as our dividend is in AX and we want a 32bit division. After the division AX
holds the quotient and DX holds the remainder. Actually the remainder is only in DL
since the remainder can be from 0 to 9.043-045 The remainder is converted into its
ASCII representation and saved on the stack. The count of digits on the stack is
incremented as well.046-047 If the quotient is zero, all digits have been saved on the
stack and if it is non-zero, we have to repeat the process to print the next digit.049 DI is
initialized to point to the top left of the screen, called the cursor home. If the screen
location is to become a parameter, the value loaded in DI will change.051-053 A digit is
popped off the stack, the attribute byte is appended to it and it is displayed on the
screen.054-055 The next screen location is two bytes ahead so DI is incremented by two.
The process is repeated CX times which holds the number of digits pushed on the
stack.057-064 We pop the registers pushed and “ret 2” to discard the only parameter on
the stack.066-070 The main program clears the screen and calls the print num
subroutine to print 4529 on the top left of the screen.
==============================================================
Program No.25 Example 6.4
; hello world at desired screen location
[org 0x0100]
jmp start
message: db 'hello world' ; string to be printed
length: dw 11 ; length of the string
;;;;; COPY LINES 008-025 FROM EXAMPLE 6.2 (clrscr) ;;;;;
; subroutine to print a string at top left of screen
; takes x position, y position, string attribute, address of string
; and its length as parameters
printstr: push bp
mov bp, sp
push es
push ax
push cx
push si
push di
mov ax, 0xb800
mov es, ax ; point es to video base
mov al, 80 ; load al with columns per row
mull byte [bp+10] ; multiply with y position
add ax, [bp+12] ; add x position
shl ax, 1 ; turn into byte offset
mov dial ; point di to required location
mov si, [bp+6] ; point si to string
mov cx, [bp+4] ; load length of string in cx
mov ah, [bp+8] ; load attribute in ah
nextchar: mov al, [si] ; load next char of string

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
mov [es:di], ax ; show this char on screen
add di, 2 ; move to next screen location
add si, 1 ; move to next char in string
loop nextchar ; repeat the operation cx times
pop di
pop si
pop cx
pop ax
pop es
pop bp
ret 10
start: call clrscr ; call the clrscr subroutine
mov ax, 30
push ax ; push x position
mov ax, 20
push ax ; push y position
mov ax, 1 ; blue on black attribute
push ax ; push attribute
mov ax, message
push ax ; push address of message
push word [length] ; push message length
call printstr ; call the printstr subroutine
mov ax, 0x4c00 ; terminate program
int 0x21
41 Push and pop operations always operate on words; however data can be read as a
word or as a byte. For example we read the lower byte of the parameter y-position in this
case.
43 Shifting is used for multiplication by two, which should always be the case when
multiplication or division by a power of two is desired.61 The subroutine had 5
parameters so “ret 10” is used.65-74 The main program pushes 30 as x-position, 20 as
y-position meaning 30th column on 20th row. It pushes 1 as the attribute meaning low
intensity blue on black with no blinking.
===============================================================
Program No.26 Example 7.1
; clear screen using string instructions
[org 0x0100]
jmp start
; subroutine to clear the screen
clrscr: push es
push ax
push cx
push di
mov ax, 0xb800
mov es, ax ; point es to video base
xor di, di ; point di to top left column
mov ax, 0x0720 ; space char in normal attribute
mov cx, 2000 ; number of screen locations

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
cld ; auto increment mode
rep stosw ; clear the whole screen
pop di
pop cx
pop ax
pop es
ret
start: call clrscr ; call clrscr subroutine
mov ax, 0x4c00 ; terminate program
int 0x21
013 A space efficient way to zero a 16bit register is to XOR it with itself.Remember that
exclusive or results in a zero whenever the bits at the source and at the destination are
same. This instruction takes just two bytes compared to “mov di, 0” which would take
three. This is a standard way to zero a 16bit register.
cld ; auto increment mode
nextchar: lodsb ; load next char in al
stosw ; print char/attribute pair
loop nextchar ; repeat for the whole string
pop di
pop si
pop cx
pop ax
pop es
pop bp
ret 10
start: call clrscr ; call the clrscr subroutine
mov ax, 30
push ax ; push x position
mov ax, 20
push ax ; push y position
mov ax, 1 ; blue on black attribute
push ax ; push attribute
mov ax, message
push ax ; push address of message
push word [length] ; push message length
call printstr ; call the printstr subroutine
mov ax, 0x4c00 ; terminate program
int 0x21
051 Both operations are in auto increment mode. 052-053 DS is automatically
initialized to our segment. ES points to video memory. SI points to the address of our
string. DI points to the screen location. AH holds the attribute. Whenever we read a
character from the string in AL, the attribute byte is implicitly attached and the pair is
present in AX. The same effect could not be achieved with a REP prefix as the REP will
repeat LODS and then
start repeating STOS, but we need to alternate them. 054 CX holds the length of the
string. Therefore LOOP repeats for each character of the string.
============================================================

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
Program No.27 Example 7.3
; hello world printing with a null terminated string
[org 0x0100]
jmp start
message: db 'hello world', 0 ; null terminated string
;;;;; COPY LINES 005-024 FROM EXAMPLE 7.1 (clrscr) ;;;;;
; subroutine to print a string
; takes the x position, y position, attribute, and address of a null
; terminated string as parameters
printstr: push bp
mov bp, sp
push es
push ax
push cx
push si
push di
push ds
pop es ; load ds in es
mov di, [bp+4] ; point di to string
mov cx, 0xffff ; load maximum number in cx
xor al, al ; load a zero in al
repne scasb ; find zero in the string
mov ax, 0xffff ; load maximum number in ax
sub ax, cx ; find change in cx
dec ax ; exclude null from length
jz exit ; no printing if string is empty
mov cx, ax ; load string length in cx
mov ax, 0xb800
mov es, ax ; point es to video base
mov al, 80 ; load al with columns per row
mul byte [bp+8] ; multiply with y position
add ax, [bp+10] ; add x position
shl ax, 1 ; turn into byte offset
mov di,ax ; point di to required location
mov si, [bp+4] ; point si to string
mov ah, [bp+6] ; load attribute in ah
cld ; auto increment mode
nextchar: lodsb ; load next char in al
stosw ; print char/attribute pair
loop nextchar ; repeat for the whole string
exit: pop di
pop si
pop cx
pop ax
pop es
pop bp
ret 8
start: call clrscr ; call the clrscr subroutine
www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
mov ax, 30
push ax ; push x position
mov ax, 20
push ax ; push y position
mov ax, 1 ; blue on black attribute
push ax ; push attribute
mov ax, message
push ax ; push address of message
call printstr ; call the printstr subroutine
mov ax, 0x4c00 ; terminate program
int 0x21
039-040 Another way to load a segment register is to use a combination of push and
pop. The processor doesn’t match pushes and pops. ES is equalized to DS in this pair of
instructions.
==========================================================
Program No.28 Example 7.4
; hello world printing with length calculation subroutine
[org 0x0100]
jmp start
message: db 'hello world', 0 ; null terminated string
;;;;; COPY LINES 005-024 FROM EXAMPLE 7.1 (clrscr) ;;;;;
; subroutine to calculate the length of a string
; takes the segment and offset of a string as parameters
strlen: push bp
mov bp,sp
push es
push cx
push di
les di, [bp+4] ; point es:di to string
mov cx, 0xffff ; load maximum number in cx
xor al, al ; load a zero in al
repne scasb ; find zero in the string
mov ax, 0xffff ; load maximum number in ax
sub ax, cx ; find change in cx
dec ax ; exclude null from length
pop di
pop cx
pop es
pop bp
ret 4
; subroutine to print a string
; takes the x position, y position, attribute, and address of a null
; terminated string as parameters
printstr: push bp
mov bp, sp
push es
push ax

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
push cx
push si
push di
push ds ; push segment of string
mov ax, [bp+4]
push ax ; push offset of string
call strlen ; calculate string length
cmp ax, 0 ; is the string empty
jz exit ; no printing if string is empty
mov cx, ax ; save length in cx
mov ax, 0xb800
mov es, ax ; point es to video base
mov al, 80 ; load al with columns per row
mul byte [bp+8] ; multiply with y position
add ax, [bp+10] ; add x position
shl ax, 1 ; turn into byte offset
mov di,ax ; point di to required location
mov si, [bp+4] ; point si to string
mov ah, [bp+6] ; load attribute in ah
cld ; auto increment mode
nextchar: lodsb ; load next char in al
stosw ; print char/attribute pair
loop nextchar ; repeat for the whole string
exit: pop di
pop si
pop cx
pop ax
pop es
pop bp
ret 8
start: call clrscr ; call the clrscr subroutine
mov ax, 30
push ax ; push x position
mov ax, 20
push ax ; push y position
mov ax, 0x71 ; blue on white attribute
push ax ; push attribute
mov ax, message
push ax ; push address of message
call printstr ; call the printstr subroutine
mov ax, 0x4c00 ; terminate program
int 0x21
036 The LES instruction is used to load the DI register from BP+4 and the ES register
from BP+6. 065 The convention to return a value from a subroutine is to use the AX
register. That is why AX is not saved and restored in the subroutine.
==========================================================
Program No.29 Example 7.5

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
; scroll up the screen
[org 0x0100]
jmp start
; subroutine to scroll up the screen
; take the number of lines to scroll as parameter
scrollup: push bp
mov bp,sp
push ax
push cx
push si
push di
push es
push ds
mov ax, 80 ; load chars per row in ax
mul byte [bp+4] ; calculate source position
mov si, ax ; load source position in si
push si ; save position for later use
shl si, 1 ; convert to byte offset
mov cx, 2000 ; number of screen locations
sub cx, ax ; count of words to move
mov ax, 0xb800
mov es, ax ; point es to video base
mov ds, ax ; point ds to video base
xor di, di ; point di to top left column
cld ; set auto increment mode
rep movsw ; scroll up
mov ax, 0x0720 ; space in normal attribute
pop cx ; count of positions to clear
rep stosw ; clear the scrolled space
pop ds
pop es
pop di
pop si
pop cx
pop ax
pop bp
ret 2
start: mov ax,5
push ax ; push number of lines to scroll
call scrollup ; call the scroll up subroutine
mov ax, 0x4c00 ; terminate program
int 0x21
===========================================================
Program No.30 Example 7.6
; scroll down the screen
[org 0x0100]
jmp start
; subroutine to scrolls down the screen
www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
; take the number of lines to scroll as parameter
scrolldown: push bp
mov bp,sp
push ax
push cx
push si
push di
push es
push ds
mov ax, 80 ; load chars per row in ax
mul byte [bp+4] ; calculate source position
push ax ; save position for later use
shl ax, 1 ; convert to byte offset
mov si, 3998 ; last location on the screen
sub si, ax ; load source position in si
mov cx, 2000 ; number of screen locations
sub cx, ax ; count of words to move
mov ax, 0xb800
mov es, ax ; point es to video base
mov ds, ax ; point ds to video base
mov di, 3998 ; point di to lower right column
std ; set auto decrement mode
rep movsw ; scroll up
mov ax, 0x0720 ; space in normal attribute
pop cx ; count of positions to clear
rep stosw ; clear the scrolled space
pop ds
pop es
pop di
pop si
pop cx
pop ax
pop bp
ret 2
start: mov ax,5
push ax ; push number of lines to scroll
call scrolldown ; call scroll down subroutine
mov ax, 0x4c00 ; terminate program
int 0x21
===========================================================
Program No.31 Example 7.7
; comparing null terminated strings
[org 0x0100]
jmp start
msg1: db 'hello world', 0
msg2: db 'hello WORLD', 0
msg3: db 'hello world', 0
;;;;; COPY LINES 028-050 FROM EXAMPLE 7.4 (strlen) ;;;;;
www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
; subroutine to compare two strings
; takes segment and offset pairs of two strings to compare
; returns 1 in ax if they match and 0 other wise
strcmp: push bp
mov bp,sp
push cx
push si
push di
push es
push ds
lds si, [bp+4] ; point ds:si to first string
les di, [bp+8] ; point es:di to second string
push ds ; push segment of first string
push si ; push offset of first string
call strlen ; calculate string length
mov cx, ax ; save length in cx
push es ; push segment of second string
push di ; push offset of second string
call strlen ; calculate string length
cmp cx, ax ; compare length of both strings
jne exitfalse ; return 0 if they are unequal
mov ax, 1 ; store 1 in ax to be returned
repe cmpsb ; compare both strings
jcxz exitsimple ; are they successfully compared
exitfalse: mov ax, 0 ; store 0 to mark unequal
exitsimple: pop ds
pop es
pop di
pop si
pop cx
pop bp
ret 8
start: push ds ; push segment of first string
mov ax, msg1
push ax ; push offset of first string
push ds ; push segment of second string
mov ax, msg2
push ax ; push offset of second string
call strcmp ; call strcmp subroutine
push ds ; push segment of first string
mov ax, msg1
push ax ; push offset of first string
push ds ; push segment of third string
mov ax, msg3
push ax ; push offset of third string
call strcmp ; call strcmp subroutine
mov ax, 0x4c00 ; terminate program
int 0x21
www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
005-007 Three strings are declared out of which two are equal and one is different.
044-045 LDS and LES are used to load the pointers to the two strings in DS:SI and
ES:DI.
070 Since there are 4 parameters to the subroutine “ret 8” is used.
====================================================
Program No.32 Example 8.1
; hooking divide by zero interrupt
[org 0x0100]
jmp start
message: db 'You divided something by zero.', 0
;;;;; COPY LINES 028-050 FROM EXAMPLE 7.4 (strlen) ;;;;;
;;;;; COPY LINES 005-024 FROM EXAMPLE 7.1 (clrscr) ;;;;;
;;;;; COPY LINES 050-090 FROM EXAMPLE 7.4 (printstr) ;;;;;
; divide by zero interrupt handler
myisrfor0: push ax ; push all regs
push bx
push cx
push dx
push si
push di
push bp
push ds
push es
push cs
pop ds ; point ds to our data segment
call clrscr ; clear the screen
mov ax, 30
push ax ; push x position
mov ax, 20
push ax ; push y position
mov ax, 0x71 ; white on blue attribute
push ax ; push attribute
mov ax, message
push ax ; push offset of message
call printstr ; print message
pop es
pop ds
pop bp
pop di
pop si
pop dx
pop cx
pop bx
pop ax
iret ; return from interrupt
; subroutine to generate a divide by zero interrupt
genint0: mov ax, 0x8432 ; load a big number in ax

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
mov bl, 2 ; use a very small divisor
div bl ; interrupt 0 will be generated
ret
start: xor ax, ax
mov es, ax ; load zero in es
mov word [es:0*4], myisrfor0 ; store offset at n*4
mov [es:0*4+2], cs ; store segment at n*4+2
call genint0 ; generate interrupt 0
mov ax, 0x4c00 ; terminate program
int 0x21
93-101 We often push all registers in an interrupt service routine just to be sure that no
unintentional modification to any register is made.Since any code may be interrupted an
unintentional modification will be hard to debug 103-104 Since interrupt can be called
from anywhere we are not sure about the value in DS so we reset it to our code segment.
========================================================
Program No.33 Example 8.2
; print string using bios service
[org 0x0100]
jmp start
message: db 'Hello World'
start: mov ah, 0x13 ; service 13 - print string
mov al, 1 ; subservice 01 – update cursor
mov bh, 0 ; output on page 0
mov bl, 7 ; normal attrib
mov dx, 0x0A03 ; row 10 column 3
mov cx, 11 ; length of string
push cs
pop es ; segment of string
mov bp, message ; offset of string
int 0x10 ; call BIOS video service
mov ax, 0x4c00 ; terminate program
int 0x21
007 The sub-service are versions of printstring that update and do not update the cursor
after printing the string etc. 008 Text video screen is in the form of pages which can be
upto 32. At one time one page is visible which is by default the zeroth page unless we
change it
============================================================
Program No.34 Example 8.3
; print string and keyboard wait using BIOS services
[org 0x100]
jmp start
msg1: db 'hello world', 0
msg2: db 'hello world again', 0
msg3: db 'hello world again and again', 0
;;;;; COPY LINES 005-024 FROM EXAMPLE 7.1 (clrscr) ;;;;;
;;;;; COPY LINES 050-090 FROM EXAMPLE 7.4 (printstr) ;;;;;
;;;;; COPY LINES 028-050 FROM EXAMPLE 7.4 (strlen) ;;;;;

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
start: mov ah, 0x10 ; service 10 – vga attributes
mov al, 03 ; subservice 3 – toggle blinking
mov bl, 01 ; enable blinking bit
int 0x10 ; call BIOS video service
mov ah, 0 ; service 0 – get keystroke
int 0x16 ; call BIOS keyboard service
call clrscr ; clear the screen
mov ah, 0 ; service 0 – get keystroke
int 0x16 ; call BIOS keyboard service
mov ax, 0
push ax ; push x position
mov ax, 0
push ax ; push y position
mov ax, 1 ; blue on black
push ax ; push attribute
mov ax, msg1
push ax ; push offset of string
call printstr ; print the string
mov ah, 0 ; service 0 – get keystroke
int 0x16 ; call BIOS keyboard service
mov ax, 0
push ax ; push x position
mov ax, 0
push ax ; push y position
mov ax, 0x71 ; blue on white
push ax ; push attribute
mov ax, msg2
push ax ; push offset of string
call printstr ; print the string
mov ah, 0 ; service 0 – get keystroke
int 0x16 ; call BIOS keyboard service
mov ax, 0
push ax ; push x position
mov ax, 0
push ax ; push y position
mov ax, 0xF4 ; red on white blinking
push ax ; push attribute
mov ax, msg3
push ax ; push offset of string
call printstr ; print the string
mov ah, 0 ; service 0 – get keystroke
int 0x16 ; call BIOS keyboard service
mov ax, 0x4c00 ; terminate program
int 0x21
099-100 This service has no parameters so only the service number is initialized in AH.
This is the only service so there is no sub-service number as well. The ASCII code of the
char pressed is returned in AL after this service.

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
=============================================================
FAQ of CS401(Latest Updated)
Question: What is Computer Architecture
Answer: Computer Architecture is the science and art of selecting and interconnecting hardware compo
functional, performance and cost goals. Computer architecture is not about using computers to de
and protocols (including formats and standards that different hardware/software must comply
which define a computer system. Computer architecture features can be available to application
in several modes, including a protected mode. For example, the system-level features of com
memory management, (2) protection, (3) multitasking, (4) input/output, (5) exceptions and mult
processing and multiprocessing, (8) debugging, and (9) cache management

Question: Explain Segment Override prefix


Answer: To override the association for one instruction of one of the registers BX, BP, SI or DI, we u
example “mov ax, [cs:bx]” associates BX with CS for this one instruction. The processor places
called a prefix.No prefix is needed or placed for default association. Opcode has not changed,
default association to association with the desired segment register for this one instruction.

Question: What is offset?


Answer: A distance from a given paragraph boundary in memory. The offset usually is given as a number

Question: What is Subroutine?


Answer: A self-contained coding segment designed to do a specific task, sometimes referred to as procedu

Question: Explain Segmented memory model


Answer: The segmented memory model allows multiple functional windows into the main memory, a co
processor sees code from the code window and data from the data window. The size of one wi
the maximum memory iAPX88 can access is 1MB which can be accessed with 20 bits.
Question: What is Address wraparound?
Answer: In physical address calculation a carry if generated is dropped without being stored anywhere, fo
the access under consideration is [bx+0x0100]. The effective address will be 0200 and the physic
21bit answer and cannot be sent on the address bus which is 20 bits wide. The carry is dropped a
our physical memory has wrapped around at its very top.

Question: Explain Linear memory model.


Answer: In linear memory model the whole memory appears like a single array of data. 8080 and 8085 c
using the 16 lines of their address bus.

Question: What's the difference between .COM and .EXE formats?


Answer: To oversimplify: a .COM file is a direct image of how the program will look in main memory,
further relocation when it is run (and so it begins with a relocation header). A .COM file is limite
but a .EXE file can have as many segments as your linker will handle and be as large as RAM
doesn't matter. DOS knows that a file being loaded is in .EXE format if its first two bytes are M
be in .COM format. Actually they must be less than 0xFF00 bytes long, since the PSP, which i

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
within those 64K, is 256 bytes long. Then CAN use many segments, but they don't have to. I
converted to an .EXE file by adding an appropriate header to it. There are some other difference
segment .EXE file (both of which must be smaller than 64K).The entry point of the .COM file
point of the .EXE file can be at any address. The stack size of the .COM file is the remainder o
code image, while the stack size if the single segment .EXE file can be set at any size as long
stack can be smaller in the .EXE file.

Question: Is MS-DOS Dead?


Answer: No. Though Microsoft may not be actively developing MS-DOS there are still many comput
Microsoft Windows. The current versions of Microsoft Windows will also run most MS-DOS p
dead, and will most- likely never die just as Commodore-64s and Amigas have not completely
life in embedded systems. Other parties continue to develop MS-DOS compatible operating syste
have a "Command Prompt" which is similar to the orignal MS-DOS command prompt.

Question: How can I read a character without echoing it to the screen, and without waiting for the user to press the Enter key?
Answer: In Assembly language, execute INT 21 AH=8; AL is returned with the character from standar
don't want to allow redirection, or you want to capture Ctrl-C and other special keys, use INT
code in AH and ASCII code (if possible) in AL, but AL=E0 with AH nonzero indicates that o
pressed. (If your BIOS doesn't support the extended keyboard, use INT 16 AH=0 not 10.)
Question: What is NASM?
Answer: NASM, the Netwide Assembler, is a free assembler for Intel 80x86 series of microprocessors. N
with MS-DOS, but it will also work under Windows 95, Linux, and OS/2.

Question: How can my program tell if it's running under Windows?


Answer: Execute INT 2F AX=4680. If AX returns 0, you're in Windows real mode or standard mode (o
call INT 2F AX=1600. If AL returns something other than 0 or 80, you're in Windows 386 enhan

Question: What is Term CACHE?


Answer: Cache A small fast memory holding recently accessed data, designed to speed up subsequent a
applied to processor-memory access but also used for a local copy of data accessible over a netw
written to, main memory a copy is also saved in the cache, along with the associated main m
addresses of subsequent reads to see if the required data is already in the cache. If it is (a cache
and the main memory read is aborted (or not started). If the data is not cached (a cache miss) th
and also saved in the cache. The cache is built from faster memory chips than main memory so
complete than a normal memory access. The cache may be located on the same integrated cir
reduce the access time. In this case it is often known as {primary cache} since there may be a lar
the CPU chip. The most important characteristic of a cache is its hit rate - the fraction of all m
from the cache. This in turn depends on the cache design but mostly on its size relative to the m
the cost of fast memory chips. The hit rate also depends on the access pattern of the particular
addresses being read and written). Caches rely on two properties of the access patterns of m
something is accessed once, it is likely to be accessed again soon, and spatial locality - if on
nearby memory locations are also likely to be accessed. In order to exploit spatial locality, cache
time, a "cache line" or "cache block". Main memory reads and writes are whole cache lines. W
main memory, the data is first written to the cache on the assumption that the processor will p

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
different policies are used. In a write-through cache, data is written to main memory at the same
cache it is only written to main memory when it is forced out of the cache. If all accesses we
policy, every write to the cache would necessitate a main memory write, thus slowing the sy
However, statistically, most accesses are reads and most of these will be satisfied from the c
write-back because an entry that is to be replaced can just be overwritten in the cache as it wil
memory whereas write-back requires the cache to initiate a main memory write of the flushed e
by a main memory read. However, write-back is more efficient because an entry may be written
main memory access.

Question: What is difference b/w assembler and disassembler?


Answer: Assembler An assembler is a program that takes basic computer instructions and converts t
computer's processor can use to perform its basic operations. Some people call these instruction
the term assembly language. In programming terminology, to disassemble is to convert a prog
form (sometimes called object code) into a representation in some form of assembler language
program used to accomplish this is called a disassembler, because it performs the inverse o
Disassembly is a type of reverse engineering. Another such program, called a decompiler, conve
a higher-level language.

Question: What are the functions of Parity and Sign flag?


Answer: Dear Student

P Parity Parity is the number of “one” bits in a binary number. Parity is


either odd or even. This information is normally used in
communications to verify the integrity of data sent from the
sender to the receiver.
S Sign Flag A signed number is represented in its two’s complement form
in the computer. The most significant bit (MSB) of a negative
number in this representation is 1 and for a positive number it
is zero. The sign bit of the last mathematical or logical
operation’s destination is copied into the sign flag.
Thanks
Question: WHAT IS MACHINE LANGUAGE?
Answer: Although programmers tend to use C or C++ or Pascal these days, the language closest to the PC
one second during a PCS powered on lifetime passes where the computer is not executing machin

Question: WHEN TO USE ASSEMBLY LANGUAGE


Answer: I personally think that except as a learning exercise it is a waste of time writing something in ASM
in a high-level language. Assembly language fits for the following: * Low level control. When
control registers of the processor, as when entering protected mode. * Speed. Programs written
can execute 10-100 times the speed of BASIC, and about twice as fast as a program written in
Critical sections of programs written in higher level languages can be written in assembly to spee
When you write a TSR for example this is very useful. Writing interrupt handlers is where as
language is very flexible and powerful; anything that the hardware of the computer is capable of

Question: What are interrupts?

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
Answer: The hardware and software designed for original PC communicated with the CPU by means of
of signals called interrupts. When a device or a program needed some action on the part of the C
an interrupt signal. The CPU would sort out the priority of the incoming interrupt requests, w
handled first (it is common for the CPU to be handling several interrupts concurrently) and then
interrupt (the Interrupt Request Handler) by examining the Interrupt Vector Table. Each interr
allocated four bytes in the vector table. These four bytes serve as an address pointer to the actual
interrupt. These routines may be stored in the ROM BIOS or more commonly in system RAM (w
are often uploaded to provide faster access). The interrupt vector table is first initialized by the S
to it's contents as first the ROM Extensions and later the operating system files are loaded. The
interrupt vector table provides a means to easily expand operating system services by making
Interrupt Handler.

Question: What are registers?


Answer: One of a small number of high-speed memory locations in a computer's CPU. Registers differ fro
in several respects: There are only a small number of registers (the "register set"), typically 32 i
e.g. SPARC, have as many as 144. A register may be directly addressed with a few bits. In co
words of main memory (RAM), requiring at least twenty bits to specify a memory location
specified indirectly, using an {indirect addressing} mode where the actual memory address is h
typically, two registers can be read and a third written -- all in a single cycle. Memory is slower
cycles.

Question: What is control bus and what function it performs?


Answer: The physical connections that carry control information between the CPU and other devices within
bus carries actual data that is being processed, the control bus carries signals that report the status
one line of the bus is used to indicate whether the CPU is currently reading from or writing to main
Question: What do you mean by Peripherl devices?
Answer: Peripherals Any piece of hardware connected to a computer; any part of the computer outside t
input or output device connected to a computer. Some examples of peripherals are keyboards, mi
and tape drives, microphones, speakers, joysticks, plotters, and cameras.

Question: What is difference b/w physical and logical address?


Answer: The segment, offset pair is called a logical address, while the 20bit address is a physical addr
addressing is a mechanism to access the physical memory. However I recommend you to read t
in handouts to get you understand well.

Question: What is difference between DATA LABEL and CODE LABEL?


Answer: Data Label is the label that we use to define data as we defined memory locations num1,num2 ..
the label that we have on code as we see in case of conditional jump (Label l1) and is normally u

Question: What is Segment Wrap Around?


Answer: Dear Student For the whole megabyte we need 20 bits while CS and IP are both 16bit register
20bit number out of the two 16bit numbers. Consider that the segment value is stored as a 20 bit
and the offset value is stored as another 20 bit number with the upper four bits zeroed. The two a

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
address. A carry if generated is dropped without being stored anywhere and the phenomenon is c

Question: What is BIOS and how it can be updated?


Answer: Dear Student

One of the most common uses of Flash memory is for the basic input/output system of your com
(pronounced "bye-ose"). On virtually every computer available, the BIOS makes sure all the other chip
together. 

What BIOS Does?

The BIOS software has a number of different roles, but its most important role is to load the operating sy
and the microprocessor tries to execute its first instruction, it has to get that instruction from somewhe
system because the operating system is located on a hard disk, and the microprocessor cannot get to it w
The BIOS provides those instructions. Some of the other common tasks tha
A power-on self-test (POST) for all of the different hardware components in the system to make

Activating other BIOS chips on different cards installed in the computer - For example, SCSI and grap
chips. 

Providing a set of low-level routines that the operating system uses to interface to different hardware de
BIOS its name. They manage things like the keyboard, the screen, and the serial and parallel ports, es

Managing a collection of settings for the hard


The BIOS is special software that interfaces the major hardware components of your computer with the o
a Flash memory chip on the motherboard, but sometimes the chip is another type of ROM.

When you turn on your computer, the BIOS does several things. This is its usual sequence:

1. Check the CMOS Setup for custom settings


2. Load the interrupt handlers and device drivers
3. Initialize registers and power management
4. Perform the power-on self-test (POST)
5. Display system settings
6. Determine which devices are bootable
7. Initiate the bootstrap sequence

Updating BIOS

Occasionally, a computer will need to have its BIOS updated. This is especially true of older machines. A
BIOS needs to change in order to understand the new hardware. Since the BIOS is stored in some form
upgrading most other types
To change the BIOS itself, you'll probably need a special program from the computer or BIOS manufactu
information displayed on system startup or check with your computer manufacturer to find out what type o
manufacturer's Web site to see if an upgrade is available. Download the upgrade and the utility program n
and update are combined in a single file to download. Copy the program, along with the BIOS update, on
with the floppy disk in the drive, and the program erases the old BIOS and writes the new one. You can
BIOS at BIOS Upgrades. 

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
Question: What is Interrupt vector Table?
Answer: Dear Student

The correlation process from the interrupt number to the interrupt handler uses a table called interru
physical memory address zero. Each entry of the table is four bytes long containing the segment an
corresponding interrupt number. The first two bytes in the entry contain the offset and the next two bytes
rule of putting the more significant part (segment) at a higher address is seen here as well. Mathematical
while the segment will be at nx4+2. One entry in this table is called a vector. If the vector is changed for in
to the new handler whose address is now placed at those four bytes. INT 1 vector occupies location 4, 5
occupies locations 8, 9, 10, and 11. As the table is located in RAM it can be changed anytime. Imm
mapping is changed and now the interrupt will result in execution of the new routine. This indirection gives

Question: What are the terms ASCII CODE and SCAN CODE?
Answer: Dear Student

Scan Code

Each key on the keyboard is assigned a unique number called a Scan Code; When a key is pre
corresponding scan code to the computer. Scan code table is given on MDB of Lecture#24.

ASCII Code

I/O devices such as the video monitor and printer are character oriented, and programs such as
exclusively. Like all data, characters must be coded in binary in order to be processed by the computer.
characters is ASCII (American Standard Code for Information Interchange) code.

Question: What is Virtual Machine?


Answer: Dear Student

Virtual machine is a term used by Sun Microsystems, developers of the Java programming language
software that acts as an interface between compiler Java binary code and the microprocessor (or "hardw
program's instructions. Once a Java virtual machine has been provided for a platform, any Java progr
bytecode) can run on that platform. Java was designed to allow application programs to be built that could
to be rewritten or recompiled by the programmer for each separate platform. Java's virt
The Java virtual machine specification defines an abstract rather than a real "machine" (or processor) a
registers, a stack, a "garbage heap," and a method area. The real implementation of this abstract or logi
code that is recognized by the real processor or be built into th

The output of "compiling" a Java source program (a set of Java language statements) is called byteco
interpret the bytecode one instruction at a time (mapping it to a real microprocessor instruction) or the by
real microprocessor using what is called a just-in-time compiler. 

Question: What are Registers and why these are needed?


Answer: Registers are like a scratch pad ram inside the processor and their operation is very much lik
precise locations and remember what is placed inside them. They are used when we need mo
processor at one time.

Question: What is Big-Endian and Little-Endian?


Answer: Big-endian and little-endian are terms that describe the order in which a sequence of bytes are stored

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
order in which the "big end" (most significant value in the sequence) is stored first (at the lowest storag
which the "little end" (least significant value in the sequence) is stored first. For example, in a big-endian c
hexadecimal number 4F52 would be stored as 4F52 in storage (if 4F is stored at storage address 1000, fo
In a little-endian system, it would be stored as 524F (52 at address 1000, 4F at 1001).

IBM's 370 computers, most RISC-based computers, and Motorola microprocessors use the big-endi
processors (CPUs) and DEC Alphas and at least some programs that run on them are little-endian.
Question: How we calculate Physical Address?
Answer: for the whole megabyte we need 20 bits while CS and IP are both 16bit registers. We need a mechanism
16bit numbers. Consider that the segment value is stored as a 20 bit number with the lower four bits
another 20 bit number with the upper four bits zeroed. The two are added to produce a 20bit absolute a
without being stored anywhere and the phenomenon is called address wraparound. The process is e
diagram.

   

Therefore memory is determined by a segment-offset pair and not alone by any one register which will be
register is assigned a default segment register to resolve such ambiguity. For example the program we
value of 0100 in IP register and some value say 1DDD in the CS register. Making both 20 bit numbers
offset is 00100 and adding them we get the physical memory address of 1DED0 where the opcode B8050

Question: What is a Stack?


Answer: Stack is a data structure that behaves in a first in last out manner. It can contain many elements and t
container. When an element is inserted it sits on top of all other elements and when an element is remov
removed first. To visualize the structure consider a test tube and put some balls in it. The second ball wi
come above the second. When a ball is taken out only the one at the top can be removed. The operati
stack is called pushing the element and the operation of removing an element from the top of the stack
thing pushed is popped out first; the last in first out behavior.

Some Important Terms (Updated GLOSSARY)


absolute address : A virtual (not physical) address within the process’ address space that is computed as an absolute

Address Bus : The group of bits that the processor uses to inform the memory about which element to read or wri
collectively known as the address bus. The address bus is unidirectional and address always travels
processor to memory.

Address In physical address calculation a carry if generated is dropped without being stored anywhere, fo
wraparound : BX=0100, DS=FFF0 and the access under consideration is [bx+0x0100]. The effective address w

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
and the physical address will be 100100. This is a 21bit answer and cannot be sent on the address
is 20 bits wide. The carry is dropped and just like the segment wraparound our physical memory
around at its very top.

AND operation : AND performs the logical bitwise and of the two operands (byte or word) and returns the result t
destination operand. A bit in the result is set if both corresponding bits of the original operands a
otherwise the bit is cleared

Archive bit : Used to indicate the most recently modified version of a file.

assembler : A program that translates assembly language into machine language.

Base + Index + The values of the base register, the index register, and the constant offset are all added together t
Offset Addressing : effective address. For example “mov [bx+si+300], ax” moves the word contents of the AX regist
word in memory starting at offset attained by adding BX, SI, and 300 in the current data segmen
segment association is again based on the base register.

Base + Index The value of the base register and the index register are added together to get the effective addres
Addressing : example “mov [bx+si], ax” moves the word contained in the AX register to offset attained by add
SI in the current data segment.

Based Register A base register is used with a constant offset in this addressing mode. The value contained in the
Indirect + Offset is added with the constant offset to get the effective address. For example “mov [bx+300], ax” st
Addressing : word contained in AX at the offset attained by adding 300 to BX in the current data segment.

Based Register A base register is used in brackets and the actual address accessed depends on the value containe
Indirect register.
Addressing :
Binary A binary number is expressed in the base two. Its possible value is either 0 or 1.
:

Binary coded A system of coding in which each decimal digit is as 4 binary digits.
decimal(BCD) :

Byte : A byte is a unit of 8 bits

CALL : An assembly language instruction telling the assembler to perform the subroutine.

Carry flag : The bit in the flag register that indicates whether the previous operation resulted in a carry out of
into high order bit of the resulting byte or word.
Cell width : The number of bits in a memory cell is called the cell width.

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2

Command : Command is an instruction to a computer or device to perform a specific task

Compare The operation of CMP is to subtract the source operand from the destination operand, updating th
Instruction : without changing either the source or the destination.

Data Bus : Data bus is used to move data from the memory to the processor in a read operation and from the
to the memory in a write operation.

Data Transfer Area of memory that DOS uses to store data from a file.
Area :
Debugger : A utility program that allows the programmer to execute a program one line at a time and view th
of registers and memory in order to help locate the source of bugs or other problems. Examples a
CodeView.

Declaration : A construct that associates the name and the attributes of a variable, function, or type.

Default : A setting or value that is assumed unless specified otherwise.

Direct A fixed offset is given in brackets and the memory at that offset is accessed.
addressing :

Directory : A logical grouping of files on a disk for the purpose of organizing files is known as directory. Ea
can contain files and/or other directories, so a hierarchy of files and directories can be created.
Far Jump : Far jump is not position relative but is absolute. Two byte segment and two byte offset must be g
jump. We use this when we need to go from one code segment to another. It loads CS with the se
and IP with the offset part.

Far procedure : A procedure that can be called by procedures residing in any segment.

File : A unit of information stored on a disk. Each file has a specification of the form filename. extensi
the filename identifies the file, and the 3-letter extension identifies the file type. Some standard e
are: .asm assembler source file .com executable program file .lst list file .obj object file .exe exec
program file

High-level Programming that does not need to consider, aspects of the underlying hardware and operating sy
programming :

Indexed Register An index register is used with a constant offset in this addressing mode. The value contained in t
Indirect + Offset register is added with the constant offset to get the effective address. For example “mov [si+300]
Addressing : the word contained in AX to the offset attained by adding 300 to SI in the current data segment
www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
Indexed Register An index register is used in brackets and the actual address accessed depends on the value contai
Indirect Addressing register. For example “mov [si], ax” moves the contents of the AX register to the word starting a
: contained in SI in the current data segment.

Instruction : A command that tells the processor to do something, like add two numbers or get some data from
memory.

Interrupt : An interrupt is a request for service from an external device seeking attention. The external devic
service by asserting an interrupt request line connected to the processor. The processor may or m
with the interrupt depending on whether the interrupt is masked (i.e., ignored). If the interrupt is
the processor deals with it by executing a piece of code called an interrupt handler. Once this han
been executed, the processor returns to the point that it had reached immediately before the inter

Interrupt flag : The bit in the flag register that indicates whether the CPU should handle mask able interrupts. If
set, interrupt are handled. If it is clear, interrupts are ignored.

Linear memory In linear memory model the whole memory appears like a single array of data. 8080 and 8085 co
model : total memory of 64K using the 16 lines of their address bus.
Listing File : Listing file is an optional output file from the assembly process that shows how the assembly lan
program has been translated into object code. A listing file has the extension .LST.

Local variable : A variable whose scope is confined to a particular unit of code, such as module-level code, or a p

Logical Address : The address of an operand generated by the CPU is called a logical address. The logical address
onto the actual address (physical address) of an operand by a memory management unit.

Low-level Programming that uses direct access to machine-level features such as programs that are part of a
programming : control systems

Machine language : The series of binary digits a microprocessor executes to perform individual tasks. People program
assembly language, and an assembler translates their instructions into machine language.
Memory : Memory is where data is stored. One byte allows you to store an eight digit binary number, so th
number you can store in each location is a binary 11111111, or 255 in decimal. The lowest is 0. I
use larger numbers, we group several chunks together. One common grouping is two bytes, or a
bytes together can hold a value between 0 and 65535 (2^16).

memory stack : A contiguous array of memory locations, commonly referred to as “the stack”, used in many pro
save the state of the calling procedure, pass parameters to the called procedure and store local va
the currently executing procedure.

Mnemonic : A word, abbreviation, or acronym that replaces something too complex to remember or type easi

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
example, ADC is the mnemonic for the 8086’s add-with-carry instruction. The assembler conver
machine (binary) code, so it is not necessary to remember or calculate the binary form.

Near Jump : When the relative address stored with the instruction is in 16 bits the jump is called a near jump.
jump we can jump anywhere within a segment. If we add a large number it will wrap around to t
part.

NEAR Procedure : A procedure that can only be called by another procedure residing in the same segment.

NOT operation : NOT inverts the bits (forms the one’s complement) of the byte or word operand.

Offset : A distance from a given paragraph boundary in memory. The offset usually is given as a number

Op-code : The op-code or operation code is the binary pattern that represents an instruction.

OR operation : OR operation performs the logical bitwise “inclusive or” of the two operands (byte or word) and
result to the destination operand. A bit in the result is set if either or both corresponding bits in th
operands are set otherwise the result bit is cleared

Overflow flag : The bit in the flag register that indicates whether the signed result of the preceding operation can
represented in the result byte or word.
Parameter : The name given in a procedure definition to a variable that is passed to the procedure.

Passing by reference Transferring the address of an argument to a procedure. This allows the procedure to modify the
: value

Passing by value : Transferring the value (rather than the address) of an argument to a procedure. This prevents the
from changing the argument’s original value.

Peripheral : The term peripheral is somewhat ambiguous. It is used to describe external devices like disk driv
keyboards, mouse, and displays. It is also used to describe the hardware that interfaces these dev
processor. For example, both the floppy disk controller chip that interfaces a floppy disk drive to
and the floppy disk drive itself are often called peripherals.

PROC : An assembly language directive indicating start of procedure.


Procedure call : An expression that invokes a procedure and passes actual arguments (if any) to the procedure.

Procedure A definition that specifies a procedure’s name, its formal parameters, the declarations and statem
definition : define what it does, and (optionally) its return type and storage class.

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
Procedure A procedure declaration that includes a list of the names and types of formal parameters followin
prototype : procedure name

Process : Generally, any executing program or code unit

Program : An organized list of instructions, that when executed causes the computer to work in a predeterm
Program Counter : The program counter contains the address of the next instruction to be executed. The program co
incremented after each instruction is executed.

Prompt : A message displayed at the beginning of a line by a program to request a response from the user.
prompts for commands with the current disk drive and directory name followed by an angle brac
Assembly).

Registers : A register is a piece of high-speed memory located directly on the processor. It is used to store d
processor manipulates it. On the iAPX8088, there are 14 registers.

RET : At the end of the subroutine, a RET instruction pops the old value of IP from the stack into the in
pointer, and execution resumes right where the CALL instruction left off.

Routine : A generic name for the procedure or a function


Segment : A particular area of memory of 64 K in size.

Segment Override To override the association for one instruction of one of the registers BX, BP, SI or DI, we use th
Prefix : override prefix. For example “mov ax, [cs:bx]” associates BX with CS for this one instruction. T
places a special byte before the instruction called a prefix. No prefix is needed or placed for defa
association. Opcode has not changed, but the prefix byte has modified the default association to a
with the desired segment register for this one instruction

Segment Segment wraparound occurs when during the effective address calculation a carry is generated. T
wraparound : dropped giving the effect that when we try to access beyond the segment limit, we are actually w
around to the first cell in the segment. For example if BX=9100, DS=1500 and the access is [bx+
form the effective address 9100 + 7000 = 10100. The carry generated is dropped forming the act
address of 0100.

Segmented memory The segmented memory model allows multiple functional windows into the main memory, a cod
model : data window etc. The processor sees code from the code window and data from the data window
one window is restricted to 64K. However the maximum memory iAPX88 can access is 1MB wh
accessed with 20 bits.

Shift : A shift operation moves the bits of a memory location or a data register one or more places left o
There are three types of shift (logical, arithmetic, and rotate). In a logical shift, a zero enters the b

www.vustudents.net
CS401 Assembly Lang. Prog- by Muhammad Ishfaq Page No.2
that is vacated. In an arithmetic operation, the sign bit is replicated during a shift right. In a rotate
the bit that falls off one end is copied to the vacated bit.
Short Jump : The jump in which if the offset is stored in a single byte then it is called a short jump. Conditiona
only be short. A short jump can go +127 bytes ahead in code and -128 bytes backwards and no m

Signed integer : An integer value that uses the most-significant bit to represent the value’s sign. If the bit is one, t
negative; if zero, the number is positive.

Source File : A file which contains a program written in assembly language is the source file. It is an input to t
assembler. An assembly language source file usually has the extension .ASM.

Stack : An area of memory in which data items are consecutively stored and removed on a last in, first o
stack can be used to pass parameters to procedures.

Subroutine : A self-contained coding segment designed to do a specific task, sometimes referred to as procedu
TOP of the stack : The last word of data added to the stack

Unsigned integer : An integer in which the most significant bit serves as part of the number, rather than as an indica
For example, an unsigned byte integer can have a value from 0 to 255. A signed byte integer, wh
its eighth bit for the sign, can range from -127 to +128.

Variable A statement that initializes and allocates storage for a variable of a given type.
Declaration :

Word : Two consecutive bytes of data i.e., 16 bits

XOR operation : Exclusive OR performs the logical bitwise “exclusive or” of the two operands and returns the res
destination operand. A bit in the result is set if the corresponding bits of the original operands co
opposite values (one is set, the other is cleared) otherwise the result bit is cleared.

www.vustudents.net

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