Вы находитесь на странице: 1из 119

JNTUH

CO&MP

What is assembly language?


An assembly language is a low-level programming language for a computer, or other
programmable device, in which there is a very strong correspondence between the language and
the architecture's machine code instructions. Each assembly language is specific to a particular
computer architecture, in contrast to most high-level programming languages, which are
generally portable across multiple architectures, but require interpreting or compiling.

Assembly language is converted into executable machine code by a utility program referred to as
an assembler like NASM, MASM, etc.; the conversion process is referred to as assembly, or
assembling the code.

Popular assemblers have emerged over the years for the Intel family of processors. These include
MASM (Macro Assembler from Microsoft), TASM (Turbo Assembler from Borland), NASM
(Netwide Assembler for both Windows and Linux), and GNU assembler distributed by the free
software foundation.

Assembly language uses a mnemonic to represent each low-level machine operation or opcode.
Some opcodes require one or more operands as part of the instruction, and most assemblers can
take labels and symbols as operands to represent addresses and constants, instead of hard coding
them into the program. Macro assemblers include a macroinstruction facility so that assembly
language text can be pre-assigned to a name, and that name can be used to insert the text into
other code.
For eg:
Intel assembly language provides the mnemonic MOV (an abbreviation of move) for instructions
such as this, so the machine code above can be written as follows in assembly language,
complete with an explanatory comment if required, after the semicolon. This is much easier to
read and to remember.
MOV AL, 61h

; Load AL with 97 decimal (61 hex)

An assembly program written for Intel 8080 will not run on Zilog Z80. Assemblers are
dependent on the instrucion sets of a particular microprocessor.

JNTUH

CO&MP

What are the different levels of programming languages?


Machine Language:
The fundamental language of the computers processor, also called Low Level Language.
Machine code or machine language is a set of instructions executed directly by a computer's
central processing unit (CPU).
Low level computer languages are machine codes or close to it. Computer cannot understand
instructions given in high level languages or in English. It can only understand and execute
instructions given in the form of machine language i.e. language of 0 and 1.

Advantages of Machine Language


i) It makes fast and efficient use of the computer.
ii) It requires no translator to translate the code i.e.Directly understood by the computer

Disadvantages of Machine Language:


i) All operation codes have to be remembered
ii) All memory addresses have to be remembered.
iii) It is hard to amend or find errors in a program written
In the machine language
iv) These languages are machine dependent i.e. a particular Machine language can be used on only
one type of computer

Assembly Language:
It was developed to overcome some of the many inconveniences of machine language. This is
another low level but a very important language in which operation codes and operands are given
in the form of alphanumeric symbols instead of 0s and ls. These alphanumeric symbols will be

JNTUH

CO&MP

known as mnemonic codes and can have maximum up to 5 letter combination e.g. ADD for
addition, SUB for subtraction, START,LABEL etc. Because of this feature it is also known as
Symbolic Programming Language.

Advantages of Assembly Language


i) It is easier to understand and use as compared to machine language.
ii)It is easy to locate and correct errors.
iii) It is modified easily

Disadvantages of Assembly Language


i) Like machine language it is also machine dependent.
ii) Since it is machine dependent therefore programmer should have the knowledge of the hardware
also.

High level language:


High level computer languages give formats close to English language and the purpose of
developing high level languages is to enable people to write programs easily and in their own
native language environment (English). High-level languages are basically symbolic languages
that use English words and/or mathematical symbols rather than mnemonic codes.
Types of High Level Languages
Many languages have been developed for achieving different variety of tasks, some are fairly
specialized others are quite general purpose.
These are categorized according to their use as:
a) Algebraic Formula-Type Processing: These languages are oriented towards the
computational procedures for solving mathematical and statistical problem

Examples are:

JNTUH

CO&MP

BASIC (Beginners All Purpose Symbolic Instruction Code).

FORTRAN (Formula Translation).

PL/I (Programming Language, Version 1).

ALGOL (Algorithmic Language).

APL (A Programming Language).

b) Business Data Processing:

These languages emphasize their capabilities for maintaining data processing procedures
and files handling problems.

Examples are:

COBOL (Common Business Oriented Language).

RPG (Report Program Generator

c) String and List Processing: These are used for string manipulation including search for
patterns, inserting and deleting characters.
Examples are:

LISP (List Processing).

Prolog (Program in Logic).

d) Object Oriented Programming Language

In OOP, the computer program is divided into objects. Examples are:

C++

Java

e) Visual programming language: these are designed for building Windows-based applications
Examples are:

Visual Basic

Visual Java

Visual C

JNTUH

CO&MP

Advantages of High Level Language:


Following are the advantages of a high level language:

User-friendly

Similar to English with vocabulary of words and symbols

Therefore it is easier to learn.

They require less time to write.

They are easier to maintain.

Problem oriented rather than 'machine' based.

Program written in a high-level language can be translated into many machine language
and therefore can run on any computer for which there exists an appropriate translator.

It is independent of the machine on which it is used i.e.Programs developed in high level


language can be run on any Computer

Disadvantages of High Level Language

A high-level language has to be translated into the machine language by a translator and
thus a price in computer time is paid.

The object code generated by a translator might be inefficient Compared to an equivalent


assembly language program

2. Differences between high level language and assembly level language


HIGH LEVEL LANGUAGE

ASSEMBLY LANGUAGE

High level languages are English like


statements and programs . Written in these
languages are needed to be translated into
machine language before to their execution
using a system software compiler .

It is low level programming language in which


the sequence of 0s and 1s are replaced by
mnemonic (ni-monic) codes. Typical
instruction for addition and subtraction .
Example :- ADD for addition , SUB for
subtraction etc
Although Assembly level languages are not
easy to understand they are relatively easier as
compared to machine level languages.

High level languages are easily


understandable.
The programs that are developed in high level

The programs written in this language are not

JNTUH

CO&MP

language are portable.

portable and the debugging process is also not


very easy.

In case of high level languages debugging of


the code is easy and the program written is not
machine dependent.

The programs developed in assembly language


are thoroughly machine dependent.

HLL (High Level Language) programs are


machine independent

Assembly language programs are machine


specific.

8086 assembler
Assembler

Converts assembly language programs into object files


Object files contain a combination of machine instructions, data, and information needed
to place instructions properly in memory

Assemblers need to

translate assembly instructions and pseudo instructions into machine instructions


Convert decimal numbers, etc. specified by programmer into binary

Typically, assemblers make two passes over the assembly file

First pass: reads each line and records labels in a symbol table
Second pass: use info in symbol table to produce actual machine code for
each line

JNTUH

CO&MP

Editor, Linker and Debugger


Editor:
A text editor is a type of program used for editing plain text files.
Text editors are often provided with operating systems or software development packages, and
can be used to change configuration files and programming language source code.
You need a text editor to create assembly language source files. You can use NotePad, or any
other editor that produces plain ASCII text files.

Linker:
A linker is a program that combines your program's object file created by the assembler with
other object files and link libraries, and produces a single executable program. You need a
linker utility to produce executable files. Two linkers: LINK.EXE and LINK32.EXE are
provided with the MASM 6.15 distribution to link 16-bit real-address mode and 32-bit
protected-address mode programs respectively.
Tool that merges the object files produced by separate compilation or assembly and creates an
executable file
Three tasks:
Searches the program to find library routines used by
program, e.g. printf(), math routines,
Determines the memory locations that code from each module will occupy and
relocates its instructions by adjusting absolute references
Resolves references among files

JNTUH

CO&MP

Loader:
Part of the OS that brings an executable file residing on disk into memory and starts it running

Steps
Read executable files header to determine the size of text and data segments
Create a new address space for the program
Copies instructions and data into address space
Copies arguments passed to the program on the stack
Initializes the machine registers including the stack ptr
Jumps to a startup routine that copies the programs arguments from the stack to
registers and calls the programs main routine

Debugger:
A debugger is a program that allows you to trace the execution of a program and examine
the content of registers and memory.

JNTUH

CO&MP

PROCESSOR AND MICROPROCESSOR:


Processor in general we call CPU
cpu are microprocessor but the basic difference is that a microprocessor contain a control device
but there is no control device used for cpu.
Microprocessor is a also Known as 8085 IC . This 40 pin IC is use to perform many Arithmetical
and logical Operations. This IC is use to interface different IC's to perform different work , For
Example: Providing multiple interrupts using 8259 IC. Similarly we can perform many other
operation by interfacing with other IC's. This type of IC's are used in Computers and Personal
Uses.

Commands along with description


Data Transfer Instructions

JNTUH

CO&MP

Memory/Register Transfer:
MOV -Move byte or word to register or memory
LDS, LES -Load pointer using data segment, extra segment
XCHG- Exchange byte or word
XLAT- Translate byte using look-up table

Stack Transfer:
PUSH, POP- Push word onto stack, pop word off stack

Address Transfer:
LEA -Load effective address

AH/Flag Transfer:
LAHF: Load AH from flags
SAHF: Store AH to flags

Port I/O instructions:


IN, OUT- Input byte or word from port, output word to port

Logical Instructions
NOT -Logical NOT of byte or word (one's complement)
AND- Logical AND of byte or word
OR- Logical OR of byte or word
XOR -Logical exclusive-OR of byte or word
TEST- Test byte or word (AND without storing)

Shift and Rotate Instructions


SHL, SHR -Logical shift left, right byte or word by 1 or CL
SAL, SAR -Arithmetic shift left, right byte or word by 1 or CL
ROL, ROR -Rotate left, right byte or word by 1 or CL
RCL, RCR- Rotate left, right through carry byte or word by 1 or CL

Arithmetic Instructions
ADD, SUB -Add, subtract byte or word
ADC, SBB -Add, subtract byte or word and carry (borrow)
INC, DEC -Increment, decrement byte or word
NEG -Negate byte or word (two's complement)
CMP -Compare byte or word (subtract without storing)
MUL, DIV -Multiply, divide byte or word (unsigned)
IMUL, IDIV -Integer multiply, divide byte or word (signed)
CBW, CWD -Convert byte to word, word to double word (useful
before multiply/divide)

10

JNTUH

CO&MP

AAA, AAS, AAM, AAD -ASCII adjust for addition, subtraction, multiplication,
division (ASCII codes 30-39)
DAA, DAS- Decimal adjust for addition, subtraction (binary coded
decimal numbers)

Transfer Instructions
JMP -Unconditional jump
JA (JNBE) -Jump if above (not below or equal)
JAE (JNB) -Jump if above or equal (not below)
JB (JNAE) -Jump if below (not above or equal)
JBE (JNA)- Jump if below or equal (not above)
JE (JZ) -Jump if equal (zero)
JG (JNLE) -Jump if greater (not less or equal)
JGE (JNL) -Jump if greater or equal (not less)
JL (JNGE) -Jump if less (not greater nor equal)
JLE (JNG)- Jump if less or equal (not greater)
JC, JNC -Jump if carry set, carry not set
JO, JNO -Jump if overflow, no overflow
JS, JNS -Jump if sign, no sign
JNP (JPO)- Jump if no parity (parity odd)
JP (JPE)- Jump if parity (parity even)
LOOP- Loop unconditional, count in CX
LOOPE (LOOPZ) -Loop if equal (zero), count in CX
LOOPNE (LOOPNZ) -Loop if not equal (not zero), count in CX
JCXZ- Jump if CX equals zero

Subroutine and Interrupt Instructions


CALL, RET -Call, return from procedure
INT, INTO -Software interrupt, interrupt if overflow
IRET Return from interrupt

String Instructions
MOVS -Move byte or word string
MOVSB, MOVSW -Move byte, word string
CMPS -Compare byte or word string
SCAS -Scan byte or word string
LODS, STOS- Load, store byte or word string
REP -Repeat
REPE, REPZ -Repeat while equal, zero
REPNE, REPNZ- Repeat while not equal (zero)

11

JNTUH

CO&MP

Processor Control Instructions


STC, CLC, CMC - Set, clear, complement carry flag
STD, CLD- Set, clear direction flag
STI, CLI -Set, clear interrupt enable flag
LAHF, SAHF- Load AH from flags, store AH into flags
PUSHF, POPF- Push flags onto stack, pop flags off stack
ESC -Escape to external processor interface
LOCK- Lock bus during next instruction
NOP -No operation (do nothing)
WAIT- Wait for signal on TEST input
HLT- Halt processor

Assembly language program structure in MASM


Structure of an assembly language program
Assembly language programs divide roughly into five sections

header

equates

data

body

closing
The Header

The header contains various directives which do not produce machine code
Sample header:
%TITLE "Sample Header"
.8086
12

JNTUH

CO&MP

.model small
.stack 256
MODEL Directive
. The MODEL directive selects a standard memory model for the program.
. It determines the way segments are linked together, as well as the maximum size of each
segment.
. Its format is .MODEL memory_model
. The memory_model may be Tiny, Medium, Compact, Large, Huge, or Flat.
The formats (including the leading dot) for the directives that define the stack, data, and code
segments are:
.STACK
.DATA
.CODE
Each of these directives causes the assembler to generate the required SEGMENT statement and
its matching ENDS.
The default stack size is 1024 bytes, which can be override.
Named Constants

Symbolic names associated with storage locations represent addresses


Named constants are symbols created to represent specific values determined by an
expression
Named constants can be numeric or string
Some named constants can be redefined
No storage is allocated for these values

Equates

Constant values are known as equates


Sample equate section:
Count EQU 10
Element EQU 5
Size = Count * Element
MyString EQU "Maze of twisty passages"
Size = 0
= is used for numeric values only
Cannot change value of EQU symbol
EQUated symbols are not variables

13

JNTUH

CO&MP

EQU expressions are evaluated where used; = expressions are evaluated where
defined

The Data Segment

Begins with the .data directive


Two kinds of variables, initialized and uninitialized.
Initialized variables take up space in the program's code file
Declare uninitialized variables after initialized ones so they do not take up space in
the program's code file

Reserving space for variables

Sample DATA SEGMENT


.data
numRows DB 25
numColumns DB ?
videoBase DW 0800h
DB and DW are common directives (define byte) and (define word)
The symbols associated with variables are called labels
Strings may be declared using the DB directive:
aTOm DB "ABCDEFGHIJKLM"

Program Data and Storage

Pseudo-ops to define data or reserve storage


DB - byte(s)
DW - word(s)
DD - doubleword(s)
DQ - quadword(s)
DT - tenbyte(s)
These directives require one or more operands
define memory contents
specify amount of storage to reserve for run-time data

DB or BYTE: Define Byte


. A DB (or BYTE) numeric expression may define one or more 1 byte constants, each consisting
of two hex digits.
. For unsigned data, the range of values is data, the range of values is -128
. The assembler converts numeric constants to binary object code (represented in hex).

14

JNTUH

CO&MP

DW or WORD : Define Word


. The DW directive defines items that are one word (two bytes) in length.
. A DW numeric expression may define one or more one word constants.
. For unsigned numeric data, the range of values is 0 to 65535; for signed data, the range of value
is -32768 to +32768
. The assembler converts DW numeric constants to binary
object code (represented in hex), but stores the bytes in reverse sequence.
DD or DWORD: Define Doubleword
. The DD directive defines items that are a doubleword (four byte) in length.
. A DD numeric expression may define one or more constants, each with a maximum of four
bytes ( 8 hex digit).
. For unsigned numeric data, the range of values is 0 to 4294967295; for signed data, the range is
+2147483647.
. The assembler converts DD numeric constants to binary object code (represented in hex), but
stores the bytes inreverse sequence.
DUP

Allows a sequence of storage locations to be defined or reserved

Only used as an operand of a define directive


DB 40 DUP(?)

$ sign :
$ symbol is used to terminate strings.
Str db Hello$
Strlen db $-str
An operand containing a dollar symbol, $, refers to the current value in the location counter.
Thus, in the above example $ - STRING_NAME evaluates to the number of bytes between
STRING_NAME and STRINGLEN which is the number of bytes (i.e., characters) in THE
STRING TO BE DISPLAYED
Defining Data

Numeric data values


100 - decimal
100b - binary

15

JNTUH

CO&MP

100h - hexadecimal
'100' - ASCII
"100" - ASCII
Use the appropriate DEFINE directive (byte, word, etc.)
A list of values may be used - the following creates 4 consecutive words
DW 40Ch,10b,-13,0
A ? represents an uninitialized storage location
DB 255,?,-128,'X'

Naming Storage Locations

Names can be associated with storage locations


ANum DB -4
DW 17
ONE
UNO DW 1
X DD ?
These names are called variables
ANum refers to a byte storage location, initialized to FCh
The next word has no associated name
ONE and UNO refer to the same word
X is an uninitialized doubleword

Arrays

Any consecutive storage locations of the same size can be called an array
X DW 040Ch,10b,-13,0
Y DB 'This is an array'
Z DD -109236, FFFFFFFFh, -1, 100b
Components of X are at X, X+2, X+4, X+6
Components of Y are at Y, Y+1, , Y+15
Components of Z are at Z, Z+4, Z+8, Z+12

DUP

Allows a sequence of storage locations to be defined or reserved


Only used as an operand of a define directive
DB 40 DUP(?)
DW 10h DUP(0)
DB 3 DUP("ABC")
DB 4 DUP(3 DUP (0,1), 2 DUP('$'))

Word Storage

16

JNTUH

CO&MP

Word, doubleword, and quadword data are stored in reverse byte order (in memory)
Directive
Bytes in Storage
DW 256
00 01
DD 1234567h 67 45 23 01
DQ 10
0A 00 00 00 00 00 00 00
X DW 35DAh DA 35
Low byte of X is at X, high byte of X is at X+1

The Program Body

Also known as the code segment


Divided into four columns: labels, mnemonics, operands, and comments
Labels refer to the positions of variables and instructions, represented by
the mnemonics
Operands are required by most assembly language instructions
Comments aid in remembering the purpose of various instructions

An example
Label Mnemonic Operand Comment
--------------------------------------------------------.data
exCode
DB
0
;A byte variable
myWord DW
?
;Uninitialized word var.
.code
MAIN
PROC
mov
ax,@data
;Initialize DS to address
mov
ds,ax
;of data segment
jmp
Exit
;Jump to Exit label
mov
cx,10
;This line skipped!
Exit:
mov
ah,04Ch
;DOS function: Exit prog
mov
al, exCode
;Return exit code value
int
21h
;Call DOS. Terminate prog
MAIN
ENDP
;End Program
END
MAIN
; and specify entry point

The Label Field

Labels mark places in a program which other instructions and directives reference
Labels in the code segment always end with a colon
Labels in the data segment never end with a colon
Labels can be from 1 to 31 characters long and may consist of letters, digits, and the
special characters ? . @ _ $ %

17

JNTUH

CO&MP

If a period is used, it must be the first character


Labels must not begin with a digit
The assembler is case insensitive

Legal and Illegal Labels

Examples of legal names


COUNTER1
@character
SUM_OF_DIGITS
$1000
DONE?
.TEST
Examples of illegal names
TWO WORDS contains a blank
2abc begins with a digit
A45.28 . not first character
YOU&ME contains an illegal character

The Mnemonic Field

For an instruction, the operation field contains a symbolic operation code (opcode)
The assembler translates a symbolic opcode into a machine language opcode
Examples are: ADD, MOV, SUB
In an assembler directive, the operation field contains a directive (pseudo-op)
Pseudo-ops are not translated into machine code; they tell the assembler to do
something

The Operand Field

For an instruction, the operand field specifies the data that are to be acted on by the
instruction. May have zero, one, or two operands
NOP
;no operands -- does nothing
INC AX
;one operand -- adds 1 to the contents of AX
ADD WORD1,2 ;two operands -- adds 2 to the contents
; of memory word WORD1
In a two-operand instruction, the first operand is the destination operand. The second
operand is the source operand.
For an assembler directive, the operand field usually contains more information about
the directive.

18

JNTUH

CO&MP

The Comment Field

A semicolon marks the beginning of a comment field


The assembler ignores anything typed after the semicolon on that line
It is almost impossible to understand an assembly language program without good
comments
Good programming practice dictates a comment on almost every line

Good and Bad Comments

Don't say something obvious, like


MOV CX,0 ;move 0 to CX
Instead, put the instruction into the context of the program
MOV CX,0 ;CX counts terms, initially 0
An entire line can be a comment, or be used to create visual space in a program
;
; Initialize registers
;
MOV AX,0
MOV BX,0

The Closing

The last lines of an assembly language program are the closing


Indicates to assembler that it has reached the end of the program and where the entry
point is
MAIN ENDP
;End of program
END MAIN ; entry point for linker use
END is a pseudo-op; the single "operand" is the label specifying the beginning of
execution, usually the first instruction after the .code pseudo-op

Assembling a Program

The source file of an assembly language program is usually named with an extension
of .asm
edit myprog.asm
The source file is processed (assembled) by the assembler (MASM) to produce an
object file (.obj)
masm myprog produces myprog.obj
The object file must be linked by the linker (LINK) to produce an executable file
(.exe)
link myprog produces myprog.exe

Using the Debugger

19

JNTUH

CO&MP

Useful for logic errors that the assembler misses


To use the debugger on myprog.asm
td myprog

.COM and .EXE files

The .COM code file format is a relic of the first version of MS-DOS
Not recommended for general purposes
All code, data, and the stack occupy one 64K segment (Borland's "tiny" model)
.EXE code files are more efficient in use of RAM
Data and code occupy separate segments
The programmer is responsible for setting up the data and code segments properly

Ending a Program

All programs, upon termination, must return control back to another program -- the
operating system
Under MS-DOS, this is COMMAND.COM
This is done by doing a DOS system call

ADDRESSING MODES
Addressing mode indicates a way of locating data or operands. Depending upon the data types
used in the instruction and the memory addressing modes, any instruction may belong to one or

20

JNTUH

CO&MP

more addressing modes, or some instruction may not belong to any of the addressing modes.
Thus the addressing modes describe the types of operands and the way they are accessed for
executing an instruction. Here, we will present the addressing modes of the instructions
depending upon their types. According to the flow of instruction execution, the instructions may
be categorized as
(i)

Sequential control flow instructions and

(ii)

Control transfer instructions.

Sequential control flow instructions are the instructions, which after execution, transfer control to
the next instruction appearing immediately after it (in the sequence) in the program. For
example, the arithmetic, logical, data transfer and processor control instructions are sequential
control flow instructions. The control transfer instructions, on the other hand, transfer control to
some predefined address somehow specified in the instruction after their execution. For example,
INT, CALL, RET and JUMP instructions fall under this category.
The addressing modes for sequential control transfer instructions are explained as follows:
Immediate: In this type of addressing, immediate data is a part of instruction, and appears in the
form of successive byte or bytes.
Example: MOV AX, 0005H
In the above example, 0005H is the immediate data. The immediate data may be 8-bit or 16-bit
in size.

Direct: In the direct addressing mode, a 16-bit memory address (offset) is directly specified in
the instruction as a part of it.
Example: MOV AX, [5000H]
Here, data resides in a memory location in the data segment, whose effective address may be
computed using 5000H as the offset address and content of DS as segment address. The effective
address, here, is 10H*DS+5000H.
Register: In register addressing mode, the data is stored in a register and it is referred using the
particular register. All the registers, except IP, may be used in this mode.
Example: MOV BX, AX.

21

JNTUH

CO&MP

Register Indirect: Sometimes, the address of the memory location, which contains data or
operand, is determined in an indirect way, using the offset registers. This mode of addressing is
known as register indirect mode. In this addressing mode, the offset address of data is in either
BX or SI or DI registers. The default segment is either DS or ES. The data is supposed to be
available at the address pointed to by the content of any of the above registers in the default data
segment.
Example: MOV AX, [BX]
Here, data is present in a memory location in DS whose offset address is in BX. The effective
address of the data is given as 10H*DS+ [BX].
Indexed: In this addressing mode, offset of the operand is stored in one of the index registers.
DS and ES are the default segments for index registers SI and DI respectively. This mode is a
special case of the above discussed register indirect addressing mode.
Example: MOV AX, [SI]
Here, data is available at an offset address stored in SI in DS. The effective address, in this case,
is computed as 10H*DS+ [SI].

Register Relative: In this addressing mode, the data is available at an effective address formed
by adding an 8-bit or 16-bit displacement with the content of any one of the registers BX, BP, SI
and DI in the default (either DS or ES) segment. The example given before explains this mode.
Example: MOV Ax, 50H [BX]
Here, effective address is given as 10H*DS+50H+ [BX].
Based Indexed: The effective address of data is formed, in this addressing mode, by adding
content of a base register (any one of BX or BP) to the content of an index register (any one of SI
or DI). The default segment register may be ES or DS.
Example: MOV AX, [BX] [SI]
Here, BX is the base register and SI is the index register. The effective address is computed as
10H*DS+ [BX] + [SI].
Relative Based Indexed: The effective address is formed by adding an 8-bit or 16-bit
displacement with the sum of contents of any one of the bases registers (BX or BP) and any one
of the index registers, in a default segment.
22

JNTUH

CO&MP

Example: MOV AX, 50H [BX] [SI]


Here, 50H is an immediate displacement, BX is a base register and SI is an index register. The
effective address of data is computed as 160H*DS+ [BX] + [SI] + 50H.
For the control transfer instructions, the addressing modes depend upon whether the destination
location is within the same segment or a different one. It also depends upon the method of
passing the destination address to the processor. Basically, there are two addressing modes for
the control transfer instructions, viz. inter-segment and intra-segment addressing modes.
If the location to which the control is to be transferred lies in a different segment other than the
current one, the mode is called inter-segment mode. If the destination location lies in the same
segment, the mode is called intra-segment.

9. Intra-segment direct mode: In this mode, the address to which the control is to be transferred
lies in the same segment in which the control transfer instruction lies and appears directly in the
instruction as an immediate displacement value. In this addressing mode, the displacement is
computed relative to the content of the instruction pointer IP.
The effective address to which the control will be transferred is given by the sum of 8 or 16 bit
displacement and current content of IP. In case of jump instruction, if the signed displacement (d)
is of 8 bits (i.e. 128<d<+128), we term it as short jump and if it is of
16 bits (i.e. 32768<+32768), it is termed as long jump.

23

JNTUH

CO&MP

10. Intra-segment Indirect Mode: In this mode, the displacement to which the control is to be
transferred, is in the same segment in which the control transfer instruction lies, but it is passed
to the instruction indirectly. Here, the branch address is found as the content of a register or a
memory location. This addressing mode may be used in unconditional branch instructions.
11. Inter-segment Direct Mode: In this mode, the address to which the control is to be
transferred is in a different segment. This addressing mode provides a means of branching from
one code segment to another code segment. Here, the CS and IP of the destination address are
specified directly in the instruction.

12. Inter-segment Indirect Mode: In this mode, the address to which the control is to be
transferred lies in a different segment and it is passed to the instruction indirectly, i.e. contents of
a memory block containing four bytes, i.e. IP (LSB), IP (MSB), CS (LSB) and CS (MSB)
sequentially. The starting address of the memory block may be referred using any of the
addressing modes, except immediate mode.

Opcode
An opcode is short for 'Operation Code'.
An opcode is a single instruction that can be executed by the CPU. In machine language it is a
binary or hexadecimal value such as 'B6' loaded into the instruction register.
In assembly language mnemonic form an opcode is a command such as MOV or ADD or JMP.

24

JNTUH

CO&MP

For example:
MOV, AL, 34h
The opcode is the MOV instruction. The other parts are called the 'operands'.
Operands are manipulated by the opcode. In this example, the operands are the register named
AL and the value 34 hex.

Instruction set: Each instruction in the instruction set describes one particular CPU operation.
Each instruction is represented in both assembly language by the mnimonics and machine
language (binary) by a word of 32 bits subdivided into several fields.

There are different types of instructions:


1.

Computational Instructions
These instructions are for arithmetic or logic manipulations. In general they operate on
two operands and store the result.

25

JNTUH

CO&MP

$rd

$rs * $rt

where

op: opcode specifying the arithmetic/logic operation to be performed;

$rd: destination register in which the result is to be stored;

$rs: source register containing the 1st operand;

$rt: source register containing the 2nd operand.

Opcode can be: add, sub, mult, div, and, or, etc.
$rd, $rs, $rt can be any of the 32 registers.

Note:

26

JNTUH

CO&MP

The destination register is specified in the first field following the opcode field in
the assembly language instruction, but the last 5-bit field in the binary machine
language instruction.

In all R-type data manipulation instructions (arithmetic, logical, shift), the


operations are specified by the function field (6 least significant bits) in the binary
instruction, with the opcode field (6 most significant bits) all equal to zero.

Note:
Immediate mode - replacing $rt by a constant:

where op can only be: add, and, or.

2.

Shift Instructions

where op can be
arithmetic), and

(shift left logical)


(shift right logical) or
(shift right
specifies the number of bits to shift. The shift amount can also be

27

JNTUH

CO&MP

specified by a variable in a register, such as the example below ($t1 holds the shift
amount):

Examples:

3.

Data Transfer Instructions


These instructions transfer data back and forth between the MM and the CPU.

Load word from MM to register:

$rd

Memory[offset + $rs]

where

lw: the opcode for load word;

$rd: destination register into which the word is to be loaded;

$rs: source register (e.g., an index number of an array);

offset: (e.g., the beginning address of the array in memory).

effective MM address: offset + $rs

28

JNTUH

CO&MP

Store word from register to memory:

$rs

Memory[offset + $rd]

where

4.

sw: the opcode for save word;

$rs: source register whose content is to be stored;

$rd: destination register, e.g., an index number of an array;

offset: e.g., the beginning address of the array in memory.

MM address: offset + $rd

Program Control
Usually the program is executed in the straight line fashion, i.e., the next instruction to be
executed is the one that follows the previous one currently being executed. But some time it is
needed to conditionally or unconditionally jump to some other part of the program (e.g.,
functions, loops, etc.) by the program control instructions.

Branch to a labeled statement if two variables are equal:


29

JNTUH

CO&MP

or not equal:

where

beq (bne): branch if equal (not equal);

$rd, $rs: two registers holding the variables;

L1: label for the target statement.

Set a register to 1 if first variable is smaller than the second, set the
register to 0 otherwise.

where
slt: set if less than
$rs, $rt: registers containing two variables to be compared;

30

JNTUH

CO&MP

$rd: register to be set to 1 if $rs < $rt, or 0 otherwise.


Immediate mode -- replacing $rt by a constant:

set $rd to 1 if $rs < constant.

Jump unconditionally to a certain labeled statement:

Jump unconditionally to a certain statement whose address is given in a


register:

Jump unconditionally to a subroutine (or function, procedure, etc.) whose


address is given as a symbol SubroutineAddress:

31

JNTUH

CO&MP

Operations related to function calls:


Branch to a subroutine by jal (jump and link)
update PC ( PC<- PC+4) to point to the next instruction;
save content of PC into register $ra ($31) as the return address;
3. load starting address of subroutine (symbolized as SubroutineAddress) to
PC.
Return to calling routine:
To return from subroutine to the calling routine, the last statement of the subroutine
must be:

32

JNTUH

CO&MP

Recursion: For recursive subroutine calls, previous content of $ra ($31) needs to be stored
in a stack in the memory.

BCD
Binary coded decimal (BCD) is a system of writing numerals that assigns a four-digit binarycode
to each digit 0 through 9 in a decimal (base-10) numeral. The four-bit BCD code for any
particular single base-10 digit is its representation in binary notation, as follows:
0 = 0000
1 = 0001
2 = 0010
3 = 0011
4 = 0100
5 = 0101
6 = 0110
7 = 0111

33

JNTUH

CO&MP

8 = 1000
9 = 1001
Numbers larger than 9, having two or more digits in the decimal system, are expressed digit by
digit. For example, the BCD rendition of the base-10 number 1895 is
0001 1000 1001 0101
The binary equivalents of 1, 8, 9, and 5, always in a four-digit format, go from left to right.
The BCD representation of a number is not the same, in general, as its simple binary
representation. In binary form, for example, the decimal quantity 1895 appears as
11101100111
Other bit patterns are sometimes used in BCD format to represent special characters relevant to a
particular system, such as sign (positive or negative), error condition, or overflow condition.
The BCD system offers relative ease of conversion between machine-readable and humanreadable numerals. As compared to the simple binary system, however, BCD increases the circuit
complexity. The BCD system is not as widely used today as it was a few decades ago, although
some systems still employ BCD in financial applications.

Unpacked BCD
Unpacked BCD representation contains only one decimal digit per byte. The digit
is stored in the least significant 4 bits; the most significant 4 bits are not relevant to
the value of the represented number.
Packed BCD
Packed BCD representation packs two decimal digits into a single byte.
Decimal
0
1
2
3
4
5
6
7
8
9
10

Binary
0000 0000
0000 0001
0000 0010
0000 0011
0000 0100
0000 0101
0000 0110
0000 0111
0000 1000
0000 1001
0000 1010

BCD
Unpacked
0000 0000
0000 0001
0000 0010
0000 0011
0000 0100
0000 0101
0000 0110
0000 0111
0000 1000
0000 1001
0000 0001 0000 0000

34

Packed
0000 0000
0000 0001
0000 0010
0000 0011
0000 0100
0000 0101
0000 0110
0000 0111
0000 1000
0000 1001
0001 0000

JNTUH

CO&MP

11
12
13
14
15
16
17
18
19
20

0000 1011
0000 1100
0000 1101
0000 1110
0000 1111
0001 0000
0001 0001
0001 0010
0001 0011
0001 0100

0000 0001 0000 0001


0000 0001 0000 0010
0000 0001 0000 0011
0000 0001 0000 0100
0000 0001 0000 0101
0000 0001 0000 0110
0000 0001 0000 0111
0000 0001 0000 1000
0000 0001 0000 1001
0000 0010 0000 0000

0001 0001
0001 0010
0001 0011
0001 0100
0001 0101
0001 0110
0001 0111
0001 1000
0001 1001
0010 0000

Invalid BCD Numbers


These binary numbers are not allowed in the BCD code: 1010, 1011, 1100, 1101, 1110,
1111
Packing a Two-Byte BCD
To pack a two-byte unpacked BCD number into a single byte creating a packed BCD number,
shift the upper byte left four times, then OR the results with the lower byte.
For example,
0000 0111 0000 1001(unpacked BCD)

0111 1001(packed BCD)

0000 0111 << 4


0111 0000 + 0000 1001

=
=

0111 0000 (SHIFT LEFT 4)


0111 1001 (OR)

Converting between Decimal and BCD


From Decimal to Unpacked BCD: To convert a decimal number into an unpacked BCD
number, assign each decimal digit its 8-bit binary equivalent.
For example,
194(base 10) = 00000001 00001001
00000100(unpacked BCD)

(base
10)
(BCD)

0000000 00001001 0000010


1
0
MSB
LSB
From Decimal to Packed BCD: To convert a decimal number into a packed BCD number,
assign each digit of the decimal to its 4-bit equivalent, padding the upper nybble with zeroes if
necessary.

35

JNTUH

CO&MP

For example,
238(base 10) = 00000010 00111000(packed BCD)

(base 10)

0010
0011 1000 (BCD)
MSB
LSB
From BCD to Decimal: To convert a BCD into a decimal number, just reverse the appropriate
process from above; beginning with the LSB, group the binary digits by either 4 or 8 bits for
packed and unpacked, respectively, then convert each set into its decimal equivalent.
Converting between Binary and BCD
From Binary to Unpacked BCD: To convert a binary number into an unpacked BCD, divide
the binary number by decimal 10 and place the quotient in the most significant byte and the
remainder in the least significant byte.

For example,
00110101(base 2) = 00000101 00000011(unpacked BCD)
0011 0101
0000 1010

=
=

53(base 2)
10(base 10)

0000 0101

with a remainder of
0000 0011

0000 0101

0000 0011

MSB

LSB

From Two-Byte Unpacked BCD to Binary: To convert from a two-byte unpacked BCD to a
binary number, multiply the most significant byte of the BCD by decimal ten, then add the
product to the least significant byte.
For example,
00001001 00000010(unpacked BCD) = 01011100(base 2)

0000 1001
0000 1010

=
=

9
10(base 10)

0101 1010

90(base 10)

36

JNTUH

CO&MP

0101 1010
+ 0000 0010

=
=

90(base 10)
2

0101 1100

92(base 10)

ASCII Representation of Digits


ASCII digits are examples of unpacked binary coded decimals. A digit is represented as
its 4-bit binary equivalent, which is stored in the lower nibble.
The upper nibble contains 011 and has no bearing on the value of the represented number.
Short for American Standard Code for Information

Interexchange, ASCII is an industry standard, which assigns letters, numbers, and


other characters within the 256 slots available in the 8-bit code.
The ASCII table is divided in 3 different sections.

Non printable, system codes between 0 and 31.


Lower ASCII, between 32 and 127. This table originates from the older, American
systems, which worked on 7-bit character tables.
Higher ASCII, between 128 and 255. This portion is programmable; characters are based
on the language of your operating system or program you are using. Foreign letters are
also placed in this section.

37

JNTUH

CO&MP

Interrupts
An interrupt is the method of processing the microprocessor by peripheral device.
An interrupt is used to cause a temporary halt in the execution of program.
Microprocessor responds to the interrupt with an interrupt service routine, which is
short program or subroutine that instructs the microprocessor on how to handle the
interrupt.

38

JNTUH

CO&MP

PROGRAMS
8-BIT Addition
.model small
.data
n1 db 01h
n2 db 03h
n3 db ?
.code
mov ax,@data
mov ds,ax
mov ax,00h
mov bl,n1
mov al,bl
mov bl,n2
add al,bl
mov n3,al
mov dl,n3
mov ax,4c00h
int 21h
end

OUTPUT:
AX = 0004

39

JNTUH

CO&MP

8-BIT Subtraction
.model small
.data
n1 db 05h
n2 db 03h
n3 db ?
.code
mov ax,@data
mov ds,ax
mov ax,0000h
mov al,n1
sub al,n2
mov n3,al

mov ax,4c00h
int 21h

end

OUTPUT:
AX = 0002

40

JNTUH

CO&MP

8-BIT Multiplication
.model small
.data
n1 db 05h
n2 db 04h
n3 db ?
.code
mov ax,@data
mov ds,ax
mov ax,00h
mov al,n1
mul n2
mov n3,al
int 21h
end

OUTPUT:
AX = 0014

41

JNTUH

CO&MP

8-BIT Division
.model small
.data
n1 db 04h
n2 db 02h
n3 db ?

.code
mov ax,@data
mov ds,ax

mov al,n1
mov ah,00h
mov bl,n2
div bl

mov ah,4ch
int 21h

end

42

JNTUH

CO&MP

OUTPUT:
AX = 0002

16-BIT Addition
.model small
.data
n1 dw 09h
n2 dw 09h
n3 dw ?
.code
mov ax,@data
mov ds,ax
mov ax,00h
mov ax,n1
add ax,n2

mov n3,ax
mov dx,n3
int 21h

end

OUTPUT:

43

JNTUH

CO&MP

AX = 0012

16-BIT Subtraction
.model small
.data
n1 dw 09h
n2 dw 05h
n3 dw ?
.code
mov ax,@data
mov ds,ax
mov ax,00h
mov ax,n1
sub ax,n2

mov n3,ax
mov dx,n3
int 21h
end

OUTPUT:

44

JNTUH

CO&MP

AX = 0004

16-BIT Multiplication
.model small
.data
NUM DW 1234H,1234H
PROD DW 2 DUP(0)
.code
mov ax,@data
mov ds,ax

LEA SI,NUM ; SI pointed to the Multiplicand


MOV AX,[SI] ; Multiplicand has to be in AX register
MOV BX,[SI+2] ; SI+2 pointed to the Multiplier and move it to BX
MUL BX ;Perform the multiplication
MOV PROD,AX ;32 bit product stored in DX-AX registers
MOV PROD+2,DX
MOV AH,4CH
INT 21H
end

OUTPUT:

45

JNTUH

CO&MP

AX = 5A90
DX=014B

16-BIT Division
.model small
.data
NUM1 DW 4567H,2345H
NUM2 DW 4111H
QUO DW 2 DUP(0)
REM DW 1 DUP(0)
.code
mov ax,@data
mov ds,ax

MOV AX,NUM1 ;Move the lower bit of Dividend to AX


MOV DX,NUM1+2
DIV NUM2
MOV QUO,AX
MOV REM,DX
MOV AH,4CH
INT 21H
End

OUTPUT:

46

JNTUH

CO&MP

AX = 8AC5
DX=0952

32-BIT Addition
.model small
.data
NUM1 DW 0FFFFH,0FFFFH
NUM2 DW 1111H,1111H
SUM DW 4 DUP(0)
.code
mov ax,@data
mov ds,ax

MOV AX,NUM1
ADD AX,NUM2
MOV SUM,AX
MOV AX,NUM1+2
ADC AX,NUM2+2
;Move LSB of NUM1 to AX
;Add LSB of NUM2 to AX
;Store the LSB in SUM
;Move MSB of NUM1 to AX
;Add MSB of NUM2 to AX
JNC DOWN ; Check for carry
MOV SUM+4,01H

47

JNTUH

CO&MP

DOWN: MOV SUM+2,AX


MOV AH,4CH
INT 21H
end
INPUT:
0FFFFFFFFH, 011111111H

OUTPUT:
0111111110H

48

JNTUH

CO&MP

32-BIT Subtraction
.model small
.data
NUM1 DW 2345H,6762H
NUM2 DW 1111H,1111H
DIF DW 2 DUP(0)
.code
mov ax,@data
mov ds,ax

MOV DS,AX
LEA SI,NUM1
LEA DI,NUM2
MOV AX,[SI]
MOV BX,[DI]
SUB AX,BX
MOV DIF,AX
INC SI
; SI pointed to the LSB of NUM1
; DI pointed to the LSB of NUM2
; Move the content of SI to AX
; Move the content of DI to BX

49

JNTUH

CO&MP

; Subtract from BX to AX
; Store the LSB result in DIF
;Update SI to point the MSB of NUM1(if
;ADD SI,02 instruction its affect carry flag)

INC SI
INC DI
INC DI
MOV AX,[SI]
MOV BX,[DI]
;Update DI to point the MSB of NUM2
; Move the content of SI to AX
; Move the content of DI to BX
SBB AX,BX ; Subtract with borrow from BX to AX
MOV DIF+2,AX
MOV AH,4CH
INT 21H
end

INPUT:
2345 6762H
1111 1111H

OUTPUT:
1234 5651H

50

JNTUH

CO&MP

32-BIT Division
.model small
.data
n1 dd 12345678h
n2 dw 207fh
.code
mov ax,@data
mov ds,ax

mov ax,n1

;mov lower 16 bits

mov dx,n1+2
mov bx,n2

div bx

mov ah,4ch
int 21h

end

51

JNTUH

CO&MP

OUTPUT:
AX = 0004

Add all the elements of an Array


.model small
.data
n1 db 01h,02h,03h,04hsum db ?

.code
mov ax,@data
mov ds,ax

mov al,n1
add al,n1+1
add al,n1+2
add al,n1+3
mov sum,al

int 21h
end

52

JNTUH

CO&MP

OUTPUT:
AX = 000A

ASCII
.model small

.data
n1 db '5'

.code
mov ax,@data
mov ds,ax

mov al,n1

mov ah,4ch
int 21h
end

OUTPUT
AX=4C35

53

JNTUH

CO&MP

Find minimum of two numbers


.model small
.data
n1 db 04h
n2 db 05h
.code
mov ax,@data
mov ds,ax

mov al,n1
cmp al,n2

jnc l2
mov dl,n1
jmp l3

l2: mov dl,n2


l3: mov ah,4ch
int 21h
54

JNTUH

CO&MP

end

OUTPUT:
DX = 0004

Decimal Addition
.model small
.data
n1 dw 04d
n2 dw 05d
n3 dw ?
.code
mov ax,@data
mov ds, ax

mov ax, 00h

;clear ax

mov ax,n1
add ax,n2
mov n3,ax

int 21h

end

55

JNTUH

CO&MP

OUTPUT:
AX = 0009

Sort the elements in descending order


.model small
.data
n db 04h,02h,06h,05h,01h
len db 05h
result db ?
.codemov ax,@data
mov ds,ax
mov si,offset n
mov di,si
mov cl,len
l1:
mov ch,cl
sub ch,01h
mov al,[si]
mov ah,00h

;clearing

mov di,si

56

JNTUH

CO&MP

l2:
cmp ch,00h
jz l4
inc di
mov bl,[di]
mov bh,00h
cmp al,bl
jnc l3

;xchg ax,bx
mov [si],bl
mov [di],al
xchg ax,bx
l3:
dec ch
jmp l2
l4:
dec cl
inc si
cmp cl,00h
jnz l1
;printing
mov si,offset n
57

JNTUH

CO&MP

mov cl,len
print:
mov al,[si]
inc si
dec cl
cmp cl,00h
jnz print
exit:
mov ah,4ch
int 21h
end

OUTPUT:
AX = 0006
AX = 0005
AX = 0004
AX = 0002
AX = 0001

58

JNTUH

CO&MP

Factorial
.model small
.data
n dw 03h
fact dw ?
.code
mov ax,@data
mov ds,ax
mov ax,00h
mov ax,01h
mov cx,n
loop1:
mul cx
loop loop1
mov fact,ax
mov ah,4ch
int 21h
end

59

JNTUH

CO&MP

OUTPUT:
AX = 0006

Perform Addition using a Function


.model small
.data
n1 dw 01h
n2 dw 02h
.code
main proc
mov ax,@data
mov ds,ax
call funct
mov ah,4ch
int 21h
main endp

funct proc
mov ax,n1
add ax,n2
ret
60

JNTUH

CO&MP

funct endp

end

OUTPUT:
AX = 0003

Hexadecimal to BCD
.model small
.data
n1 db 25h
n2 db 49h
.code
mov ax,@data
mov ds,ax

mov al,n1
add al,n2

mov dl,al

daa

mov ah,4ch
int 21h
61

JNTUH

CO&MP

end

OUTPUT:
AX = 4874

Input/output
.model small
.code
mov dl,'a'; store ascii character a to the dl
mov ah,2h; msdos character output function
int 21h

mov ax,4c00h; return to ms-dos


int 21h
end

INPUT:

OUTPUT:
a

62

JNTUH

CO&MP

Input array
.model small
.data
n1 db ?
.code
mov ax,@data
mov ds,ax
lea bx,n1
mov cl,05
l1:
cmp cl,00h
jz l2
mov ah,01h
int 21h
mov [bx],al
inc bx
dec cl

63

JNTUH

CO&MP

jmp l1
l2:
mov ah,4ch
int 21h
end

INPUT:

14729

Pack to UP
.model small
.data
n1 db 26h
n2 db 49h
.code
mov ax,@data
mov ds,ax
mov al,n1
add al,n2
daa

;get the packed BCD value

mov dh,al
mov cl,04h
shr dh,cl

;clearing lower half 4 bits

mov dl,al

64

JNTUH

CO&MP

and dl,0fh

;clearing upper half 4 bits

mov ah,4ch
int 21h
end

OUTPUT:

AX=4875
DX=0705

Shift and Rotate


.model small
.data
n1 dw 0110b
.code
mov ax,@data
mov ds,ax
mov cl,01h
mov ax,n1

;logical left shift

shl ax,cl
mov ax,n1
shr ax,cl
mov ax,n1

;logical right shift


;arithmatic left shift

sal ax,cl
mov ax,n1

;arithmatic right shift


65

JNTUH

CO&MP

sar ax,cl
mov ax,n1
rol ax,cl
mov ax,n1
ror ax,cl

mov ax,n1

;rotate left through carry(carry will be MSB)

rcl ax,cl

mov ax,n1
rcr ax,cl

;rotate right through carry(carry will be LSB)

mov ah,4ch
int 21h

end

66

JNTUH

CO&MP

String Compare
.model small
.data
str1 db "Hello World$"
str2 db "Hello World$"
msg1 db "Strings are equal$"
msg2 db "Strings are not equal$"

.code
mov ax,@data
mov ds,ax

;initialize ds

mov es,ax

; and es

mov si,offset str1 ;si points to first string


mov di,offset str2 ;di points to second string

cld

;left to right processing


67

JNTUH

CO&MP

mov cx,10

;# of chars in strings

repe cmpsb

;compare string bytes

je equal

;string1 precedes string2

jne notEqual

;string2 precedes string1

equal:
mov dx, offset msg1
mov ah,09h
int 21h
jmp EXIT

notEqual:
mov dx,offset msg2
mov ah,09h
int 21h
jmp EXIT

EXIT:
mov ah,4ch
int 21h

end

OUTPUT:

68

JNTUH

CO&MP

Strings are equal

TASK-1
1) Write assembly language programs to evaluate the expressions:
i) a=b+c-d*e
ii) z=x*y+w-v+u/k
a. Considering 8-bit,16-bit and 32-bit binary numbers as b,c,d,e.
b. Considering 2-digit, 4-digit and 8-digit BCD numbers.
Take the input in consecutive memory locations and also Display the results by using int
xx of 8086. Validate program for the boundary conditions.
i) Considering 8-bit binary numbers as b,c,d,e.
.model small
.data

b db 1000b
c db 0010b
d db 0011b
e db 0010b
a db ?

69

JNTUH

CO&MP

.code

mov ax, @data


mov ds, ax

mov ax, 00h


mov al, b
add al, c

sub al, d
mul e
mov a, al
mov dl, a
mov ax, 4ch
int 21h
end

OUTPUT:
DX=000E

i) Considering 16-bit binary numbers as b,c,d,e.


.model small
.data
b dw 09h
c dw 01h
d dw 02h

70

JNTUH

CO&MP

e dw 03
a dw ?
.code
mov ax, @data
mov ds, ax
mov ax, 00h
mov ax, b
add ax, c
sub ax, d
mul e
mov a, ax
mov dx, a
mov ax, 4ch
int 21h
end

OUTPUT:
DX=0018

ii) Considering 8-bit binary numbers:


.model small
.data

x db 0010b
y db 0111b
w db 0001b
v db 0010b

71

JNTUH

CO&MP

u db 0001b
k db 0111b

z db ?

.code

mov ax, @data


mov ds, ax
mov ax, 00h
mov al, x
mul y
add al, w
sub al, v
add al, u
div k
mov z, al
mov dl, z

mov ax, 4ch


int 21h
end

OUTPUT:
DX= 0002

ii) Considering 16-bit binary numbers:


.model small

72

JNTUH

CO&MP

.data
x dw 02h
y dw 07h
w dw 01h
v dw 02h
u dw 01h
k dw 07h
z dw ?
.code
mov ax, @data
mov ds, ax
mov ax, 00h
mov ax, x
mul y
add ax, w
sub ax, v
add ax, u
div k
mov z, ax
mov dx, z

mov ah, 4ch


int 21h
end

73

JNTUH

CO&MP

OUTPUT:
DX= 0002

TASK-2
2) Write an ALP of 8086 to take N numbers as input. And do the following operations on
them.
a) Arrange in ascending and Descending order.
b) Find maximum and minimum
c) Find average
Considering 8-bit, 16-bit binary numbers and 2-digit, 4-digit and 8-digit BCD numbers.
Display the results by using int xx of 8086. Validate program for the boundary
conditions.
a) Arrange in ascending and Descending order.
ASCENDING ORDER:
.model small
.data
n db 04h,02h,06h,05h,01h
len db 05h
result db ?
.code
mov ax,@data

74

JNTUH

CO&MP

mov ds,ax
mov si,offset n
mov di,si
mov cl,len
l1:
mov ch,cl
sub ch,01h
mov al,[si]
mov ah,00h

;clearing

mov di,si
l2:
cmp ch,00h
jz l4
inc di
mov bl,[di]
mov bh,00h
cmp al,bl
jc l3

mov [si],bl
mov [di],al
xchg ax,bx
l3:
dec ch

75

JNTUH

CO&MP

jmp l2
l4:
dec cl
inc si
cmp cl,00h
jnz l1

;printing
mov si,offset n
mov cl,len
print:
mov al,[si]
inc si
dec cl
cmp cl,00h
jnz print
exit:
mov ah,4ch
int 21h
end

OUTPUT:

76

JNTUH

CO&MP

AX = 0001
AX = 0002
AX = 0004
AX = 0005
AX = 0006

DESCENDING ORDER:
.model small
.data
n db 04h,02h,06h,05h,01h
len db 05h
result db ?
.code
mov ax,@data
mov ds,ax
mov si,offset n
mov di,si
mov cl,len

l1:
mov ch,cl
sub ch,01h
mov al,[si]

77

JNTUH

CO&MP

mov ah,00h

;clearing

mov di,si
l2:
cmp ch,00h
jz l4
inc di
mov bl,[di]
mov bh,00h
cmp al,bl
jnc l3

mov [si],bl
mov [di],al
xchg ax,bx
l3:
dec ch
jmp l2

l4:
dec cl
inc si
cmp cl,00h
jnz l1
;printing

78

JNTUH

CO&MP

mov si,offset n
mov cl,len
print:
mov al,[si]
inc si
dec cl
cmp cl,00h
jnz print
exit:
mov ah,4ch
int 21h
end

OUTPUT:
AX = 0006
AX = 0005
AX = 0004
AX = 0002
AX = 0001

b) Find maximum and minimum


MAXIMUM:
.MODEL SMALL
.DATA
n db 07h,03h,02h,05h

79

JNTUH

CO&MP

cnt db 04h
res db 01 dup(?)
.CODE
mov ax,@data
mov ds,ax
mov ax,0000
mov cl,cnt
dec cl
mov si,offset n
mov al,[si]
up:
inc si
cmp al,[si]
jnc down
xchg al,[si]
down:
dec cl
jnz up
mov di,offset res
mov [di],al
mov ah,4ch
int 21h
END

OUTPUT:
AX = 0007

80

JNTUH

CO&MP

MINIMUM:
.MODEL SMALL
.DATA
n db 07h,03h,02h,05h
cnt db 04h
res db 01 dup(?)
.CODE
mov ax,@data
mov ds,ax
mov ax,0000
mov cl,cnt
dec cl
mov si,offset n
mov al,[si]
up:
inc si
cmp al,[si]
jc down
xchg al,[si]
down:
dec cl
jnz up
mov di,offset res
mov [di],al

81

JNTUH

CO&MP

mov ah,4ch
int 21h

END

OUTPUT:
AX = 0002

c) Find average
.MODEL SMALL
.DATA
VAL1 DB

NL1

DB

0AH,0DH,'ENTER HOW MANY NO U WANT:','$'

NL2

DB

0AH,0DH,'ENTER NO:','$'

NL3

DB

0AH,0DH,'AVEARGE:','$'

.CODE
MOV AX,@DATA
MOV DS,AX

LEA DX,NL1
MOV AH,09H
INT 21H

MOV AH,01H
INT 21H

82

JNTUH

CO&MP

SUB AL,30H

MOV CL,AL
MOV BL,AL
MOV AL,00
MOV VAL1,AL

LBL1:
LEA DX,NL2
MOV AH,09H
INT 21H
MOV AH,01H
INT 21H
SUB AL,30H

ADD AL,VAL1
MOV VAL1,AL
LOOP LBL1
LBL2:
LEA DX,NL3
MOV AH,09H
INT 21H
MOV AX,00
MOV AL,VAL1
DIV BL

83

JNTUH

CO&MP

ADD AX,3030H
MOV DX,AX
MOV AH,02H
INT 21H

MOV AH,4CH
INT 21H

END

OUTPUT:
C:\masm\8086>masm average.asm;
C:\masm\8086>link average.obj;
C:\masm\8086>average.exe
ENTER HOW MANY NO U WANT : 3
ENTER NO : 2
ENTER NO : 6
ENTER NO : 4
AVERAGE : 4

84

JNTUH

CO&MP

TASK-3
3) Write an ALP of 8086 to take a string of as input (in C format) and do the following
operations on it:
a) Find its length
b) Find it is palindrome or not
c) Find whether given string sub string or not
d) Reverse a string
e) Concatenate by taking another string
Display the result by taking int xx of 8086.

a) Length of the string


.model small
.data
str db "Hello"
strlen db $-str
.code

85

JNTUH

CO&MP

mov ax,@data
mov ds,ax
mov dx,00h

add strlen,30h ;conversion of integer into hexadecimal value


mov dl,strlen
mov ah,02h
int 21h

mov ah,4ch
int 21h

end

OUTPUT:
C:\masm\8086>masm strlen.asm;
C:\masm\8086>link strlen.obj;
C:\masm\8086>strlen.exe
5

b) Find it is palindrome or not


.model small
.data
str db "madam$"
strlen dw $-str
msg1 db "Palindrome$"

86

JNTUH

CO&MP

msg2 db "Not Palindrome$"


reverse dw ?
.code
mov ax,@data
mov ds,ax
mov es,ax

mov si,offset str


add si,strlen

dec si

;$ is removed

mov cx,strlen ;count


dec cx

mov di,offset reverse

l1:
mov dl,[si-1] ;indexing starts from 0
mov [di],dl
dec si
inc di
dec cx
cmp cx,00h
jnz l1

87

JNTUH

CO&MP

mov [di],'\$' ;terminating the string

;start comparing
mov si,offset str
mov di,offset reverse

cld

mov cx,strlen
dec cx
repe cmpsb

je pal
jne npal
jmp exit

pal:
mov dx,offset msg1
mov ah,09h
int 21h
jmp exit
npal:
mov dx,offset msg2
mov ah,09h
int 21h
jmp exit
88

JNTUH

CO&MP

exit:
mov ah,4ch
int 21h
end

OUTPUT:
C:\masm\8086>masm strpal.asm;
C:\masm\8086>link strpal.obj;
C:\masm\8086>strpal.exe
Palindrome
c) Find whether given string sub string or not
.model small
.data
str1 db "HelloWorld$"
str2 db "oWo$"
len dw $-str2-1

msg1 db "YES$"
msg2 db "NO$"

.code
;initializing data segment
mov ax,@data
mov ds,ax

mov si,offset str1

89

JNTUH

CO&MP

l1:
mov di,offset str2
mov cx,00h

;counter initialized to zero

l2:
mov al,[si]
cmp al,'$'
jz l3
inc si
mov dl,[di]
cmp dl,'$'
jz l3
cmp al,dl
jnz l1
inc di
inc cx
jmp l2

l3:
cmp cx,00h
jz NO
cmp cx,len
jnz NO

;success

90

JNTUH

CO&MP

mov dx,offset msg1


mov ah,09h
int 21h
jmp EXIT

NO:
mov dx,offset msg2
mov ah,09h
int 21h

EXIT:
mov ah,4ch
int 21h

end

OUTPUT:
C:\masm\8086>masm strsub.asm;
C:\masm\8086>link strsub.obj;
C:\masm\8086>strsub.exe
YES

d) Reverse a string
.model small
.data
str db "computer",'$'

91

JNTUH

CO&MP

strlen dw $-str
reverse dw ?
.code
mov ax,@data
mov ds,ax
mov si,offset str
add si,strlen

dec si

;$ is removed

mov cx,strlen ;count


dec cx
mov di,offset reverse
l1:
mov dl,[si-1] ;indexing starts from 0
mov [di],dl
dec si
inc di
dec cx
cmp cx,00h
jnz l1
mov [di],'\$' ;terminating the string

mov dx,offset reverse


mov ah,09h
int 21h

92

JNTUH

CO&MP

mov ah,4ch
int 21h

end

OUTPUT:
C:\masm\8086>masm strRev.asm;
C:\masm\8086>link strRev.obj;
C:\masm\8086>strRev.exe
retupmoc

e) Concatenate by taking another string


.model small
.data
str1 db "Hello$"
str2 db "World$"
str3 db ?
.code
;initializing data segment
mov ax,@data
mov ds,ax

;actual code
mov si,offset str1

;source index

mov di,offset str3

;destination index

93

JNTUH

CO&MP

;copying from source to destination


l1:
mov dl,00h
mov dl,[si]
cmp dl,'$'
jz l2
mov [di],dl
inc si
inc di
jmp l1

l2:
mov si,offset str2

l3:
mov dl,[si]
cmp dl,'$'
jz EXIT
mov [di],dl
inc si
inc di
jmp l3

EXIT:
mov [di],'\$'
mov dx,offset str3

94

JNTUH

CO&MP

mov ah,09h
int 21h

mov ah,4ch
int 21h
end
OUTPUT:
C:\masm\8086>masm strcat.asm;
C:\masm\8086>link strcat.obj;
C:\masm\8086>strcat.exe
HelloWorld

TASK-4
4) Write the ALP to implement the above operations as procedures and call
from the main procedure.
Arrange in Ascending order:
.model small
.data
n db 04h,02h,06h,05h,01h
len db 05h
result db ?
.code
main proc
mov ax,@data
mov ds,ax

95

JNTUH

CO&MP

mov si,offset n
mov di,si
mov cl,len

call ascorder
mov ah,4ch
int 21h
main endp

ascorder proc
l1:
mov ch,cl
sub ch,01h
mov al,[si]
mov ah,00h

;clearing

mov di,si

l2:
cmp ch,00h
jz l4
inc di
mov bl,[di]
mov bh,00h
cmp al,bl
jc l3

96

JNTUH

CO&MP

mov [si],bl
mov [di],al

xchg ax,bx

l3:
dec ch
jmp l2

l4:
dec cl
inc si
cmp cl,00h
jnz l1

;printing
mov si,offset n
mov cl,len
print:
mov al,[si]
inc si
dec cl
cmp cl,00h
jnz print
exit:
ret
97

JNTUH

CO&MP

ascorder endp
end

OUTPUT:
C:\masm\8086>masm ascorder.asm;
C:\masm\8086>link ascorder.obj;
C:\masm\8086>td ascorder.exe
AX = 0001
AX = 0002
AX = 0004
AX = 0005
AX = 0006
Arrange in Descending order:
.model small
.data
n db 04h,02h,06h,05h,01h
len db 05h
result db ?
.code
main proc
mov ax,@data
mov ds,ax

mov si,offset n
mov di,si
mov cl,len

98

JNTUH

CO&MP

call descorder

mov ah,4ch
int 21h
main endp

descorder proc
l1:
mov ch,cl
sub ch,01h
mov al,[si]
mov ah,00h

;clearing

mov di,si

l2:
cmp ch,00h
jz l4
inc di
mov bl,[di]
mov bh,00h
cmp al,bl
jnc l3

mov [si],bl
mov [di],al

99

JNTUH

CO&MP

xchg ax,bx

l3:
dec ch
jmp l2

l4:
dec cl
inc si
cmp cl,00h
jnz l1
;printing
mov si,offset n
mov cl,len
print:
mov al,[si]
inc si
dec cl
cmp cl,00h
jnz print

exit:
ret

100

JNTUH

CO&MP

descorder endp

end

OUTPUT:
C:\masm\8086>masm descorder.asm;
C:\masm\8086>link descorder.obj;
C:\masm\8086>td descorder.exe
AX = 0006
AX = 0005
AX = 0004
AX = 0002
AX = 0001
Find the Maximum number:
.MODEL SMALL
.DATA
n db 07h,03h,02h,05h
cnt db 04h
res db 01 dup(?)
.CODE
main proc
mov ax,@data
mov ds,ax
mov ax,0000
mov cl,cnt
dec cl

101

JNTUH

CO&MP

mov si,offset n
mov al,[si]

call maximum

mov ah,4ch
int 21h
main endp
maximum proc
up:
inc si
cmp al,[si]
jnc down
xchg al,[si]
down:
dec cl
jnz up
mov di,offset res
mov [di],al
ret
maximum endp
END

OUTPUT:
C:\masm\8086>masm max.asm;
C:\masm\8086>link max.obj;

102

JNTUH

CO&MP

C:\masm\8086>td max.exe
AX = 0007

Find the Minimum number:


.MODEL SMALL
.DATA
n db 07h,03h,02h,05h
cnt db 04h
res db 01 dup(?)
.CODE
main proc
mov ax,@data
mov ds,ax
mov ax,0000
mov cl,cnt
dec cl
mov si,offset n
mov al,[si]

call minimum

mov ah,4ch
int 21h
main endp
minimum proc
up:

103

JNTUH

CO&MP

inc si
cmp al,[si]
jc down
xchg al,[si]
down:
dec cl
jnz up
mov di,offset res
mov [di],al
ret
minimum endp

END
OUTPUT:
C:\masm\8086>masm min.asm;
C:\masm\8086>link min.obj;
C:\masm\8086>td min.exe
AX = 0001

Find the average of a given series:


.model small
.data
n db 04h,02h,06h,05h,03h
len db 05h
result db ?
.code

104

JNTUH

CO&MP

main proc

mov ax,@data
mov ds,ax
mov si,offset n

call avge

mov ah,4ch
int 21h

main endp
avge proc

mov cl,len
mov ax,00h
mov bl,len

l1:
add al,[si]
inc si
dec bl
cmp bl,00h
jnz l1

105

JNTUH

CO&MP

div cl

mov dl,al
mov ah,2
exit:
int 21h
ret
avge endp
end

OUTPUT:
AX = 0004

Find the length of a string:

.model small
.data
str db "Hello"
strlen db $-str
.code
main proc
mov ax,@data
mov ds,ax

call len

106

JNTUH

CO&MP

mov ah,4ch
int 21h
main endp
len proc
mov dx,00h
add strlen,30h ;conversion of integer into hexadecimal value
mov dl,strlen
mov ah,02h
int 21h
RET
len endp
end

OUTPUT:
C:\masm\8086>masm procstrlen.asm;
C:\masm\8086>link procstrlen.obj;
C:\masm\8086>procstrlen.exe
5

Find whether the given string is palindrome or not:


.model small
.data
str db "madam$"
strlen dw $-str
msg1 db "Palindrome$"
msg2 db "Not Palindrome$"

107

JNTUH

CO&MP

reverse dw ?
.code
main proc
mov ax,@data
mov ds,ax
mov es,ax

mov si,offset str


add si,strlen

dec si

;$ is removed

mov cx,strlen ;count


dec cx

mov di,offset reverse

call palin

mov ah,4ch
int 21h
main endp

palin proc
l1:
mov dl,[si-1] ;indexing starts from 0

108

JNTUH

CO&MP

mov [di],dl
dec si
inc di
dec cx
cmp cx,00h
jnz l1

mov [di],'\$' ;terminating the string

;start comparing
mov si,offset str
mov di,offset reverse

cld

mov cx,strlen
dec cx
repe cmpsb

je pal
jne npal
jmp exit

pal:
mov dx,offset msg1
mov ah,09h

109

JNTUH

CO&MP

int 21h
jmp exit
npal:
mov dx,offset msg2
mov ah,09h
int 21h
jmp exit
exit:
ret

palin endp

end
OUTPUT:
C:\masm\8086>masm palindrome.asm;
C:\masm\8086>link palindrome.obj;
C:\masm\8086>palindrome.exe
Palindrome

Find whether the given string is substring or not:


.model small
.data
str1 db "HelloWorld$"
str2 db "oWo$"
len dw $-str2-1
msg1 db "YES$"

110

JNTUH

CO&MP

msg2 db "NO$"
.code
main proc
;initializing data segment
mov ax,@data
mov ds,ax

mov si,offset str1

call substring

mov ah,4ch
int 21h
main endp

substring proc
l1:
mov di,offset str2
mov cx,00h

;counter initialized to zero

l2:
mov al,[si]
cmp al,'$'
jz l3
inc si
mov dl,[di]

111

JNTUH

CO&MP

cmp dl,'$'
jz l3
cmp al,dl
jnz l1
inc di
inc cx
jmp l2

l3:
cmp cx,00h
jz NO
cmp cx,len
jnz NO

;success
mov dx,offset msg1
mov ah,09h
int 21h
jmp EXIT

NO:
mov dx,offset msg2
mov ah,09h
int 21h

EXIT:

112

JNTUH

CO&MP

ret

substring endp
end

OUTPUT:
C:\masm\8086>masm substring.asm;
C:\masm\8086>link substring.obj;
C:\masm\8086>substring.exe
YES

Reverse a String:
.model small
.data
str db "computer",'$'
strlen dw $-str
reverse dw ?
.code
main proc
mov ax,@data
mov ds,ax

mov si,offset str


add si,strlen

113

JNTUH

CO&MP

dec si

;$ is removed

mov cx,strlen ;count


dec cx

mov di,offset reverse


call strev

mov ah,4ch
int 21h

main endp
strev proc
l1:
mov dl,[si-1] ;indexing starts from 0
mov [di],dl
dec si
inc di
dec cx
cmp cx,00h
jnz l1

mov [di],'\$' ;terminating the string

mov dx,offset reverse

114

JNTUH

CO&MP

mov ah,09h
int 21h

ret
strev endp

end

OUTPUT:
C:\masm\8086>masm reverse.asm;
C:\masm\8086>link reverse.obj;
C:\masm\8086>reverse.exe
retupmoc
String Concatenation:
.model small
.data
str1 db "Hello$"
str2 db "World$"
str3 db ?
.code
main proc
;initializing data segment
mov ax,@data
mov ds,ax

;actual code

115

JNTUH

CO&MP

mov si,offset str1

;source index

mov di,offset str3

;destination index

call strcat
mov ah,4ch
int 21h

main endp
strcat proc
;copying from source to destination
l1:
mov dl,00h
mov dl,[si]
cmp dl,'$'
jz l2
mov [di],dl
inc si
inc di
jmp l1
l2:
mov si,offset str2
l3:
mov dl,[si]
cmp dl,'$'
jz EXIT
mov [di],dl
inc si
116

JNTUH

CO&MP

inc di
jmp l3

EXIT:
mov [di],'\$'
mov dx,offset str3
mov ah,09h
int 21h

ret
strcat endp

end
OUTPUT:
C:\masm\8086>masm strcat.asm;
C:\masm\8086>link strcat.obj;
C:\masm\8086>strcat.exe
HelloWorld

117

JNTUH

CO&MP

TASK-5
5) Write an ALP of 8086 to find the factorial of a given number as a procedure and call
from the main program which display the result.
.model small

.data
n dw 4d

.code

main proc
mov ax,@data
mov ds,ax
call fact
mov ah,4ch
118

JNTUH

CO&MP

int 21h
main endp

fact proc
mov ax,1
mov cx,n
l1:
cmp cx,00h
jz exit
mul cx
dec cx
jmp l1
exit:
ret
fact endp

end

OUTPUT:
AX 0018

119