You are on page 1of 25

 

   Assembly Language Programming


Lab Manual
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Vision:
To empower the students to play a vital and leading role as technologist in the rapidly changing
arena of Computer Science and Engineering and also prepare them to contribute to the
advancement of society and mankind.

Mission:
The Computer Science and Engineering department would impart high quality technical
education to help the students to respond to the global happenings and take up research work to
create knowledge in the field, through rigorous and comprehensive teaching learning process and
inculcate in them the ethical and moral values for the society.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

PROGRAMME OUTCOMES (POs)

Apply the knowledge of mathematics, science and engineering fundamentals to solve complex computer
science and engineering related problems.
Identify, formulate, make literature reviews, and analyze complex computer science and engineering
problems to reach substantiated conclusions.
Design, analyze and develop solutions for complex computer science and engineering problems that meets
specified needs.
Experiment and analyze computer science and engineering problems through research-based knowledge
and research methods on real world data’s for providing valid conclusions.
Create, select, and apply appropriate techniques, resources, and modern engineering and IT tools to
complex computer science and engineering applications.
As a responsible computer science engineer of the society, will have to apply reasoning informed by the
contextual knowledge to assess societal, health, safety, legal and cultural issues and responsibilities
relevant to the professional engineering practice.
Find, understand and execute professional engineering solutions in societal and environmental contexts,
using the knowledge of computer science and engineering for sustainable development.
Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
Perform successively as an individual or as a team leader/member in interdisciplinary ventures.
Communicate engineering activities with engineering community and society, such as, being able to
comprehend and write effective reports, documentations, making effective presentations, and give
and receive clear instructions.
Apply the computer science and engineering knowledge principles in solving and managing projects as an
individual’s work or as a team in multidisciplinary environments.
Attain a strong base in the computer science and engineering field so as to recognize its need and have the
preparation and ability to engage in independent and life-long learning in the broadest context of
technological change.

PROGRAM SPECIFIC OUTCOME (PSO)

Apply innovative ideas in the design and development of software systems and applications
in the emerging areas of artificial intelligence, computer networks and information
technology.

Analyze real world problems, determine their solvability and formulate efficient solutions
by applying algorithmic techniques, software modeling, mathematical foundations and
theory of computation.

Develop computer programs by defining suitable hardware - software interfaces, choosing


appropriate programming language, utilizing the required system software tools and by
employing standard software engineering practices.
Preface

Assembly Language is a programming language that is very similar to machine language, but
uses symbols instead of binary numbers. It is converted by the assembler (e.g. Tasm and Masm)
into executable machine-language programs. To make programs in assembly language, you must
know some information about the 8086 microprocessor. The 8086 contains 14 registers. Each
register is 16 bits.

The 8086 has four groups of the user accessible internal registers. They are

1. general purpose registers


2. Segment registers.
3. pointer and index registers
4. Flag register

1.General Purpose Registers:

• AX : Accumulator register consists of two 8-bit registers AL and AH, which can be combined
together and used as a 16- bit register AX. AL in this case contains the low-order byte of the
word, and AH contains the high-order byte. Accumulator can be used for I/O operations and
string manipulation.

• BX: Base register consists of two 8-bit registers BL and BH, which can be combined together
and used as a 16-bit register BX. BL in this case contains the low-order byte of the word, and BH
contains the high-order byte. BX register usually contains a data pointer used for based, based
indexed or register indirect addressing.

• CX: Count register consists of two 8-bit registers CL and CH, which can be combined together
and used as a 16-bit register CX. When combined, CL register contains the low- order byte of the
word, and CH contains the highorder byte. Count register can be used in Loop, shift/rotate
instructions and as a counter in string manipulation,.

• DX: Data register consists of two 8-bit registers DL and DH, which can be combined together
and used as a 16-bit register DX. When combined, DL register contains the low- order byte of
the word, and DH contains the highorder byte. Data register can be used as a port number in I/O
operations. In integer 32-bit multiply and divide instruction the DX register contains high-order
word of the initial or resulting number.

2. Segment register:

• Code segment (CS) is a 16-bit register containing address of 64 KB segment with processor
instructions. The processor uses CS segment for all accesses to instructions referenced by
instruction pointer (IP) register. CS register cannot be changed directly. The CS register is
automatically updated during far jump, far call and far return instructions.

• Stack segment (SS) is a 16-bit register containing address of 64KB segment with program
stack. By default, the processor assumes that all data referenced by the stack pointer (SP) and
base pointer (BP) registers is located in the stack segment. SS register can be changed directly
using POP instruction.

• Data segment (DS) is a 16-bit register containing address of 64KB segment with program data.
By default, the processor assumes that all data referenced by general registers (AX,BX, CX, DX)
and index register (SI, DI) is located in the data segment. DS register can be changed directly
using POP and LDS instructions.

• Extra segment (ES) is a 16-bit register containing address of 64KB segment, usually with
program data. By default, the processor assumes that the DI register references the ES segment
in string manipulation instructions. ES register can be changed directly using POP and LES
instructions

3.Pointer and Index Registers:

• Instruction Pointer (IP) is a 16-bit register that contains the offset address. IP is combined
with the CS to generate the address of the next instruction to be executed.

• Stack Pointer (SP) is a 16-bit register pointing to program stack.

• Base Pointer (BP) is a 16-bit register pointing to data in stack segment. BP register is usually
used for based, based indexed or register indirect addressing.

• Source Index (SI) is a 16-bit register. SI is used for indexed, based indexed and register
indirect addressing, as well as a source data address in string manipulation instructions.

• Destination Index (DI) is a 16-bit register. DI is used for indexed, based indexed and register
indirect addressing, as well as a destination data address in string manipulation instructions.

4.Flag Register:

Flags is a 16-bit register containing nine 1-bit flags. 06 flags are status flags and 3 are Control
Flags.

•Overflow Flag (OF) - set if the result is too large positive number, or is too small negative
number to fit into destination operand.

•Direction Flag (DF) - if set then string manipulation instructions will auto-decrement index
registers. If cleared then the index registers will be auto-incremented.
•Interrupt-enable Flag (IF) - setting this bit enables maskable interrupts.

•Single-step Flag (TF) - if set then single-step interrupt will occur after the next instruction.

•Sign Flag (SF) - set if the most significant bit of the result is set.

•Zero Flag (ZF) - set if the result is zero.

•Auxiliary carry Flag (AF) - set if there was a carry from or borrow to bits 0-3 in the AL
register.

•Parity Flag (PF) - set if parity (the number of "1" bits) in the low-order byte of the result is
even.

•Carry Flag (CF) - set if there was a carry from or borrow to the most significant bit during last
result calculation.

Instruction set of 8086/8088:

8086/88 microprocessor supports the following types of instructions:


1. Data Transfer Instructions
 These instructions are used to transfer data from source to destination. 
 The operand can be a constant, memory location, register or I/O port address.
MOV – Used to copy the byte or word from the provided source to the provided
destination. [MOV D,S]
Eg: MOV AX,BX 
MOV AX<-2000H
XCHG − Used to exchange the data from two locations.[XCGH D,S]
Eg: XCHG CX,BX
XCHG [2000],AX
IN − Used to read a byte or word from the provided port to the accumulator.
Eg: IN AL,Port8 //Read byte from 8-bit port
IN AX,port16//Read word from 16-bit port
OUT − Used to send out a byte or word from the accumulator to the provided port.
Eg : OUT   port8,AL //writ byte in AL to 8-bit port
     OUT port16,AL //write word in AL to 16-bit port
LEA(Load Effective Address) : Used to load the address of operand into the provided
register.
Eg: LEA R16,EA //operands effective address is loaded in to register R16
PUSH: Used to put a word at the top of the stack.
Eg: PUSH source
    PUSH DX
POP : Used to get a word from the top of the stack to the provided location.
Eg : POP DX

2.Arithmetic Instructions
 These instructions are used to perform arithmetic operations like addition, subtraction,
multiplication, division, etc.
 ADD: Used to add the provided byte to byte/word to word.
Eg : ADD D,S //D<-D+S
 ADC : [Addition with carry] Used to add with carry.
Eg: ADC D,S //D<-D+S+CY
 SUB : Used to subtract the byte from byte/word from word.
Eg: SUB D,S // D<-D-S
 SBB : Used to perform subtraction with borrow.
Eg: SBB D,S// D<-D-S-CY
 MUL : Used to multiply unsigned byte by byte/word by word.
Eg: MUL OP //multiplication of accumulator by the source operand
  DIV : Used to divide the unsigned word by byte or unsigned double word by word.
Eg: DIV S //AL<-Q{(AX)/(S8)}
      // AH<-R{(AX)/(S8)}
 INC − Used to increment the provided byte/word by 1.
Eg : INC D  //D<-D+1
 DEC- Used to decrement the provided byte/word by 1.
Eg: DEC D // D<-D-1
 CMP : Used to compare 2 provided byte/word.
Eg: CMP D,S // D-S ,resuilt is discarded and sets the flag accordingly
3.Logical Instructions
Used to perform logical operations, such as AND,OR,XOR,NOT.
 AND:  AND OP1,OP2
 OR : OR OP1,OP2
 XOR : XOR OP1,OP2
 NOT : NOT OP
4.Process control Instructions
 HLT : (Halt the microprocessor operation)
    Syntax : HLT
 NOP: (No operation)
    Syntax : NOP
5.Program Execution Transfer Instructions
CALL − Used to call a procedure and save their return address to the stack.
 Near call : With in the segment
 Far call : Outside the segment
SYNTAX : CALL PROC
                   CALL BX (BX contains address of first instruction of proc)
 RET − Used to return from the procedure to the main program.
 SYNTAX : RET
JMP − Used to jump to the provided address to proceed to the next instruction.
 SYNTAX : JMP D (unconditional jump)
 Transfers control to another part of the program
 SYNTAX : JCC OPERAND  ( Conditional jump)
 Jumps to specified address if the condition is TRUE
JA/JNBE − Used to jump if above/not below/equal instruction satisfies.
JAE/JNB − Used to jump if above/not below instruction satisfies.
JBE/JNA − Used to jump if below/equal/ not above instruction satisfies.
JC − Used to jump if carry flag CF = 1
JE/JZ − Used to jump if equal/zero flag ZF = 1
JG/JNLE − Used to jump if greater/not less than/equal instruction satisfies.
JGE/JNL − Used to jump if greater than/equal/not less than instruction satisfies.
JL/JNGE − Used to jump if less than/not greater than/equal instruction satisfies.
JLE/JNG − Used to jump if less than/equal/if not greater than instruction satisfies.
JNC − Used to jump if no carry flag (CF = 0)
JNE/JNZ − Used to jump if not equal/zero flag ZF = 0
JNO − Used to jump if no overflow flag OF = 0
JNP/JPO − Used to jump if not parity/parity odd PF = 0
JNS − Used to jump if not sign SF = 0
JO − Used to jump if overflow flag OF = 1
JP/JPE − Used to jump if parity/parity even PF = 1
JS − Used to jump if sign flag SF = 1
6.Loop Instructions
This instruction performs a loop operation using CX register as a counter. Each time the
LOOP instruction is executed ,the counter register is decremented, then checked for 0. If
count=0, loop terminates and execution continues eith next instruction.
 LOOP − Used to loop a group of instructions until the condition satisfies, i.e., CX = 0
LOOPE/LOOPZ − Used to loop a group of instructions till it satisfies ZF = 1 & CX = 0
LOOPNE/LOOPNZ − Used to loop a group of instructions till it satisfies ZF = 0 & CX = 0
SYNTAX : LOOP label
Eg :  mov CX,10
        l1: <loop body>
        loop l1
7.String Instructions
 The string instructions perform operations on sequence of bytes or words. 
 Source string is at DS :SI
 Destination string is at ES : DI
1) MOVS :  Transfers data from one memory location to another.
(only instruction which allows memory- memory transfers in 8086)
 MOVSB : Move byte from one string to another
 MOVSW : Move word from one string to another
2) LODS : The LODS instruction loads from memory .If the operand is of one byte, it is loaded into
the AL register, if the operand is one word, it is loaded into the AX register.
 LODSB : Load string byte in to AL register [DS]:SI to AL
 LODSW : Load string word in to AX register [DS]:SI to AX
3)STOS : This instruction stores data from register (AL, AX) to memory.
 STOSB: Store byte from AL into string. AL to ES:[DI].
 STOSW: Store word from AX into string. AX to ES:[DI].
8.String comparison instruction
1) CMPS : This instruction compares two data items in memory. Data could be of a byte size,
word or doubleword.
 CMPSB : compare two string bytes
 CMPSW : compare two string words
2) SCAS − This instruction compares the contents of a register (AL, AX ) with the contents of an
item in memory.
 SCASB ,SCASW
 Repeat  Instructions
 REP − Used to repeat the given instruction till CX ≠ 0.
 REPE/REPZ − Used to repeat the given instruction until CX = 0 or zero flag ZF = 1.
 REPNE/REPNZ − Used to repeat the given instruction until CX = 0 or zero flag ZF = 0.
9.INTERRUPT INSTRUCTIONS
These instructions are used to call the interrupt during program execution.
1) INT − Used to interrupt the program during execution and calling service specified.
2) INTO − (INTERRUPT ON OVERFLOW )Used to interrupt the program during execution if OF =
1
3) IRET − (INTERRUPT RETURN) Used to return from interrupt service to the main program
Exercise-1

AIM:
1.a.Write Assembly language program to print the numbers from 0 to 9.

Program:
org 100h
.data
a db 0,1,2,3,4,5,6,7,8,9
.code
mov cx,10
mov si,0 
loop1:  
mov al,a[si]
mov dl,al
add dl,48 
mov ah,2h
int 21h
INC si
loop loop1
Hlt

Outcome:

AIM:

1.b.Write Assembly language programs to find average of numbers stored in an array.

Program:

org 100h
.data
a db 1,2,3,4,5
avg db ?
.code
mov ax,@data
mov ds,ax
mov cx,5
mov si,0
mov bl,5
loop1:
ADD al,a[si]
inc si
loop loop1
mov ah,0
div bl
mov avg,al
Hlt

Outcome:
Exercise-2

AIM:
2.a. Write Assembly language programs to find the largest number in an array 

Program:
org 100h
.data
a db 1,9,7,6 
.code
mov ax,@data
mov ds,ax
mov cx,4
mov si,0 
mov bh,a[si]
loop1: 
INC si    
cmp bh,a[si] 
Jg l1
mov bh,a[si]
l1: 
mov dl,bh
loop loop1
hlt  
Outcome:
AIM:
2.b. Write Assembly language programs to sort the numbers in ascending order. 

Program:
org 100h
.data
a db 9,8,7,6,5,4,3,2,1
.code
mov ax,@data
mov ds,ax
mov cx,9
mov si,0
bubblesort:
cmp cx,si
jz next
mov al,a[si]
mov bl,a[si+1]
cmp al,bl
ja exchange                                                             
add si,1
jmp bubblesort
exchange:
mov a[si],bl
mov a[si+1],al
add si,1
jmp bubblesort
next:
mov si,00
sub cx,1
cmp cx,0
jnz bubblesort
mov cx,9
mov si,0
loop1:
mov dl,a[si]
add dl,48
mov ah,2h
int 21h
inc si
loop loop1
Outcome:

Exercise-3
AIM:
3.a. Write Assembly language programs to find L.C.M of two numbers.     
Program:

org 100h
.data
a db 9
b db 4
lcm db ?
.code
mov ax,@data
mov ds,ax
mov ah,0
mov al,a
mov bl,b
mov bh,al
div bl
cmp ah,0
je exit
jne l1
l1:
mov ah,0
mov al,bh
add al,a
mov bh,al
div bl
cmp ah,0
je exit
jne l1
exit:
mov lcm,bh
hlt
Outcome:
AIM:
3.b. Write Assembly language programs to find G.C.D of two numbers. 
    
Program:
org 100h
.data
a db 8
b db 4
hcf db ?
.code
mov ax,@data
mov ds,ax
mov al,a
mov bl,b
mov ah,0
div bl
cmp ah,0
je exit
jne l1
l1:
mov ah,0 
mov al,a
dec bl
div bl
cmp ah,0
je exit
jne l1
exit:
mov hcf,bl
Hlt
Outcome:
Exercise-4

AIM:

4.a. Write Assembly language programs to display nth term fibonacci number.
          

Program:

org 100h
.data 
z db 10 dup(?)
b db 1
c db 1
fib db ?
.code 
mov si,0 
mov ax,@data
mov ds,ax 
mov cx,6
mov al,b
mov bl,c
mov z[si],al
mov z[si+1],bl 
l1: 
add al,bl
mov bh,al
mov al,bl
mov bl,bh 
mov z[si+2],bh
inc si
loop l1
mov fib,bl
Ret
Outcome:
AIM:
4.b. Write Assembly language programs to find the factorial of a number.
Program:

org 100h
.data
a dw 3
fact dw ?
.code
mov ax,@data
mov ds,ax
mov ax,a 
cmp ax,1  
mov dx,ax
dec dx
mov bx,dx
je exit
cmp ax,2
je exit
jne l2
l2: 
mul bx 
cmp bx,1
dec bx
je exit
jne l2 
exit:      
mov fact,ax

Ret
Outcome:
Exercise-5
AIM:
Develop an assembler to convert the given assembly language program into machine language
program by considering 8086/88 microprocessor.  

Program:

new.txt:
lda# 14ah
bun# 13ah
add@ 60dh
and# 2a9h
sub# 14ah
Python Program:

import binascii

def hexacon(k):
    z=bin(int(k, 16))[2:]
    return z

def binacon(k):
    c=hex(int(k,2))
    return c[2:]
    
o=0
with open("new.txt","r") as q:
    for l in q:
        o+=1
q.close()
x=""

j=open("binary.txt","w")
a=open("new.txt","r")
for i in range(o):
    b=a.readline()
    d={"and":"000","lda":"010","add":"001","sta":"011","bun":"100","cal":"101","sub":"110"}
    di={"cla":"7800","cma":"7400","inc":"7200","hlt":"7100","inp":"f800","out":"f400","ski":"f2
00","sko":"f100","ion":"f080","iof":"f040"}
    c=b.split()
    k=c[0]
    if k in di:
        u=di[k]
        v=hexacon(u)
        if len(v)==16:
            v=v
        else:
            v="0"+v
        j.write(v)
        x+=v
        j.write("\n")
        
    else:
        l=k
        g=c[1][:3]
        w=l[:3]
        z=d[w]
        if l[-1]=="#":
            z="0"+z
        elif l[-1]=="@":
            z="1"+z
        p=z
        q=hexacon(g)
        r=binacon(z)
        z=r+g
        n=len(q)
        b=12-n
        if n<12:
            q=("0"*b)+q
        else:
            q=q
        p=p+q
        j.write(p)
        j.write("\n")
        x+=p

a.close()
j.close()

#-------------writing------------------
original_string = x

bit_strings = [original_string[i:i + 8] for i in range(0, len(original_string), 8)]

byte_list = [int(b, 2) for b in bit_strings]

with open('byte.bin', 'wb') as f:


    f.write(bytearray(byte_list))
f.close()

#----------------reading-----------------
w=open("byte.bin","rb")
q=w.read()
k=binascii.hexlify(q)
z=str(k)
q=z[2:]
e=q[:-1]
o=0
j=4
for i in range(1,len(e),4):
    print(e[o:j])
    o+=4
    j+=4
    
w.close()

Exercise-6

  AIM:

Develop a simulator for 8086/88 microprocessor.   


Program:

import binascii

ac=0
pc=0
u=[]

#---------creating memory array-------

def create():
    for i in range(4095):
        u.append(None)

def hexacon(k):
    z=bin(int(k, 16))[2:]
    return z

#---------displaying-------------

def display(n):
    global ac
    if n==1:
        print("\n")
        print("ac is : ",ac)
    elif n==2:
        print("pc is : ",pc)
        print("\n")
    else:
        print("\n")
        g=int(input("Enter the index value: "))
        print("The value is:  ",u[g])
            
#---------memory reference-------
            
def reference(e,f):
    global ac
    global pc
    global u
    if e=="000":
        ac=ac and u[f]
    elif e=="001":
        ac=ac+u[f]
    elif e=="010":
        ac=u[f]
    elif e=="011":
        u[f]=ac
    elif e=="100":
        pc=f
    elif e=="101":
        pc=f
    elif e=="110":
        ac=ac-u[f]
        
def memory(i):
    r=hexacon(i)
    if len(r)<16:
        n=16-len(r)
        r=(("0")*n)+r
        return r
    else:
        return r

    
#---------start-------------
    
w=open("byte.bin","rb")
q=w.read()
k=binascii.hexlify(q)
w.close()
z=str(k)
q=z[2:]
e=q[:-1]
l=[]

create()#creating memory array

j=4
o=0
for i in range(1,len(e),4):
    l.append(e[o:j])
    o+=4
    j+=4

d={"000":"and","010":"lda","001":"add","011":"sta","100":"bun","101":"cal","110":"sub"}

for i in l:
    p=memory(i)
    y=p[1:4]
    n=p[0]
    #--------giving memory-----------
    u[330]=6
    u[681]=5
    u[1549]=330
    h=p[4:]
    f=int(h,2)
    if n=="0":
        f=f
    else:
       f=u[f]
    reference(y,f)
    
while True: 
    print("enter 1-Accumulator   2-Program Counter 3-Memory   4-Quit")
    print("\n")
    j=int(input("Enter the block you want to display: "))
    if j==4:
        break
    display(j)
    print("\n")

You might also like