You are on page 1of 27

Assembly Language Programming II

Instruction set

In order to write an assembly language program for a microprocessor, you must


understand the instructions supported by the device. Different microprocessors may
support different operations, however, the basic concept of assembly language
programming is very similar. Moreover, the syntax for the instruction is more or less the
same. Therefore, once you learn assembly language programming for one
microprocessor, then you can easily write programs for other microprocessors.
For example, the move operation (syntax MOV) can be found in the Intel
microprocessors, and the ADuC832 microcontroller. In PowerPC, there is the lwz, which
stands for the load operation. Other processors may use the load instruction.

The 8086 instruction set is relatively simple and it has a total of 117 basic instructions. If
you understand all basic instructions then you can fully control the 8086. Moreover, since
Intel processors are upward compatible so your assembly language program can run on
all Intel processor including the P5 or Core2 Duo!!!!

The instructions are divided into 5 groups:


Data transfer move
Arithmetic addition, subtraction, multiply, divide
Logic AND, OR, XOR
Shift
Rotate

We will go through the different groups (not different instructions) one by one, however,
for details descriptions, you should refer to the document provided by the emu8086
software (www.emu8086.com) or a proper reference.

Data transfer instructions

The main purpose of the data transfer instructions is to move data either between its
internal registers or between an internal register and a storage location in memory. The
most frequently used data transfer instruction is the move operation, mnemonic MOV.

Syntax: MOV destination, source ; move data from source to destination

The data being moved could be 16-bit or 8-bit


The system does not support moving data from one memory location to another memory
location. When the segment register is used in a data transfer operation then the move
instruction must be applied to a 16-bit data.

For example, Mov SS, data


where SS represents a segment register, such as DS, ES, then data must be a 16-bit value.
Mnemonic Meaning Format Operation Flags affected
Mov Move mov D,S (S) to (D) none

Destination (D) Source (S)


Memory AX
AX Memory
Register Register
Register Memory
Memory Register
Register Immediate
Memory Immediate
Seg-reg Reg16
Seg-reg Mem16
Reg16 Seg-reg

Mem16 Seg-reg

The above table shows the syntax for the MOV instruction and the possible combinations
for the source and destination.

Example:
MOV AL, BL ; register to register
MOV AL, 16 ; immediate (a value 16) to register

Special data transfer instructions

Exchange data between the source and destination XCHG


Syntax : XCHG AX, DX ; value in DX is stored in AX and value in AX stored
in DX

Load effective address (LEA) is a frequently used instruction for saving the offset
address of a variable. This is similar to x = &y in C++ programming!

Syntax: LEA SI, INPUT ; effective address of INPUT will be stored in SI


register
INPUT in the above example represents a variable
Since an offset address is stored so the destination must be a 16-bit register! An offset
address is a 16-bit value!!!
LEA usually is used to access data defined in the program, as shown below.
Example

LEA BX, dat


MOV AL, [BX+2]

What is inside AL if dat is defined as the following?


dat DB 11h, 22h, 33h, 44h, 55h

Load register and DS (LDS)

As its name implies, LDS will load a specified register and the DS register in a single
operation!

Syntax: LDS SI, [200] ; 4 bytes of data will be fetched, the first 2 bytes (location
200 and 201) stored in SI and the following 2 bytes (locations 202 and 203) stored in
DS.

There is also the load register and ES (LES). Similar to LDS, LES will load a specific
register and the ES register.

Arithmetic instructions

Table 1 depicts arithmetic instructions available in the 8086.


Some examples of available arithmetic operations: add, subtract, multiply, etc.
The operations can apply to unsigned value, signed value, binary bytes, words, unpacked,
packed decimal bytes, or even ASCII numbers.

Packed decimal two BCD digits are packed into a byte register or memory location.
Each BCD is 4 bits representing digit 0 to 9.
Unpacked decimal numbers are stored one BCD digit per byte
After an arithmetic operation, the flags (such as Carry, Sign, Overflow, Zero) are updated
accordingly. Based on the flag status, different operations can be performed, similar to an
IF ELSE syntax.

Table 1 Arithmetic operation of 8086

ADD Add byte or word


ADC Add byte or word with carry
Inc Increment byte or word by 1
AAA ASCII adjust for addition
DAA Decimal adjust for addition
Sub Subtract byte or word
Sbb Subtract byte or word with borrow
DEC Decrement byte or word by 1
NEG Negate byte or word
AAS ASCII adjust for subtraction
DAS Decimal adjust for subtraction
MUL Multiply byte or word unsigned
IMUL Integer multiply byte or word
AAM ASCII adjust for multiply
Div Divide byte or word unsigned
Idiv Integer divide byte or word
AAD ASCII adjust for division
CBW Convert byte to word
CWD Convert word to doubleword

Addition related operations

Mnemonic Meaning Format Operation Flags affected


Add Addition Add D, S D = S+D OF, SF, ZF, AF, PF, CF
CF = carry

ADC Add with carry ADC D, S D = S+D+CF OF, SF, ZF, AF, PF, CF
CF = carry

INC Increment by 1 INC D D = D+1 OF, SF, ZF, AF, PF


AAA ASCII adjust for AAA AF, CF, OF, SF, ZF, PF
addition undefined

DAA Decimal adjust for DAA SF, ZF, AF, PF, CF, OF
addition undefined

Destination Source
Register Register
Register Memory
Memory Register
Register Immediate
Memory Immediate
AX Immediate

Example
AL = 12H, BL = 70H
Carry = 1
ADC AL, BL
Then result is in AL = 83H
The carry is only 1-bit and it is being added to the LSB (least significant bit).

Example
BX = 1234 CX= 0123
Carry is 0
SBB BX, CX ; subtract with borrow
Give 1111

Subtraction

Mnemonic Meaning Format Operation Flags affected


Sub Subtract Sub D,S D = D-S OF, SF, ZF, AF,
CF = borrow PF, CF
Sbb Subtract with SBB D,S D = D-S-CF OF, SF, ZF, AF,
borrow PF, CF
Dec Decrement by 1 DEC D D=D-1 OF, SF, ZF, AF,
PF
Neg Negate Neg D D=0-D OF, SF, ZF, AF,
CF =1 PF, CF
DAS Decimal adjust DAS OF, SF, ZF, AF,
for subtraction PF, CF undefined

AAS ASCII adjust for AAS OF, SF, ZF, AF,


subtraction PF, CF undefined

Destination Source

Register Register

Register Memory

Memory Register

AX Immediate

Register Immediate

Memory immediate
If BX = 3AH
NEG BX
Give FFC6H

NEG make the operand negative (based on 2s complement)


Executing the NEG instruction causes the following
2s complement subtraction
00 - (BX) = 0000 + 2s complement of 3A
= 0000 + FFC6
= FFC6H

Multiplication

When multiplying 8-bit data, result is 16-bit and stored in AX (a 16-bit register).
When multiplying two 16-bit data, result is 32-bit and result stored in AX and DX.
The AX holds the LSW (Least significant word) and DX stores the MSW (Most
significant word). Only the source operand is specified in the multiply operation and
the other operand must be stored in AL, or AX. This also applies in the division
operation.
In 8-bit division, the result is stored in AH and AL. Where AH is the remainder and AL is
the quotient.
For 16-bit division, AX contains the quotient and DX contains the remainder

If AL is 1 and CL is 2, what will be the result produced in AX for

MUL CL ; this is CL * AL (unsigned)


IMUL CL ; this is CL*AL (signed)

MUL CL is unsigned multiply = FD02 (-1 = FFH; -2 = FEH so FFxFE = FD02H)


IMUL CL is signed multiply = 2 (-1*-2 = 2)

If AL = 39 and BL = 4 then to do AL / BL you should get quotient = 9 and remainder =


3

MOV AL, 39
MOV BL, 4
DIV BL ; so AL/BL and results stored in AH = 3 (remainder) and AL =9

Special functions

CBW convert byte (8-bit) to word (16-bit). So what is the additional 8 bits?
CBW fill AH with 0 if AL is positive; fill AH with 1s if AL is negative then AH
becomes FF. In doing so, the sign of the original data will be retained.
CWD convert word (16-bit) to double word (32-bit) and the DX register is used to store
the high order word.
CWD fill DX with 0 if AL is positive; fill DX with 1s if AX is negative then DX
becomes FF
Both CBW and CWD do not require operand, the data must be stored in AL or AX.

Use CBW when doing 8-bit operation, AX is used by default.


Use CWD when doing 16-bit operation, AX and DX are used by default.

What is the result of executing the following sequence of instructions?

MOV AL, A1H


CBW
CWD

Ans.
AX = FFA1 after CBW ; AL 8-bit converts to 16-bit AX
DX = FFFF after CWD ; AX is 16-bit converts to 32-bit (DX + AX)

Multiplication and division functions

Mnemonic Meaning Format Operation Flags affected


MUL Multiply MUL S AX = AL*S8 OF, CF depends on
(Unsigned) DX,AX = AX*S16 result

S, Z, A, P undefined
DIV Division DIV S AL = Q (AX/S8)
(unsigned) AH = R(AX/S8) OF, CF, SF, ZF, AF,
PF all undefined
IMUL Integer IMUL S AX = AL*S8 OF, CF depends on
multiply DX,AX=AX*S16 result
(signed) S, Z, A, P undefined
IDIV Integer divide IDIV S AX = Q(AX/S8) OF, CF, SF, ZF, AF,
(signed) AH=R(AX/S8) PF all undefined
AX = Q(DX,AX)/S16
DX=R(DX,AX)/S16
If Q is positive and
exceeds 7FFF or if Q
is negative and
becomes less than
8001 then type 0
interrupt occurs
Multiplication related functions

Mnemonic Meaning Format Operation Flags affected


AAM Adjust AL for AAM AH=Q(AL/10) SF, ZF, PF,
multiplication AL=R(AL/10) OF, AF, CF
Ascii adjust after undefined
Multiplication for
BCD values
AAD Adjust AX for AAD AL=(AH*10+AL) SF, ZF, PF,
division AH =00 OF, AF, CF
Prepare 2 BCD undefined
values for division
CBW Convert byte to CBW All bits of AH = None
word (MSB of AL)

CWD Convert word to CWD All bits of DX = none


double word MSB of AX

A simple application of assembly language programming

Try to write a simple assembly language program to convert from Centigrade (Celsius) to
Fahrenheit assuming result is an integer.
The equation for the conversion is
f = c * 9 / 5 + 32
What operations are required?
Do you need to define variables?
Sample is available in the ftp site

Logic instructions

Logic operations include: AND, OR, exclusive-OR (XOR) and NOT

Eg AND AX, BX
The above is applying logical AND to value in AX and value in BX. Result is stored in
AX. The bits in AX and BX are logical ANDed bit-by-bit.

Example:
MOV AL, 10101100B
AND AL, 11110000B ; bit by bit operation

AL 1 0 1 0 1 1 0 0
1 1 1 1 0 0 0 0
AND 1 0 1 0 0 0 0 0
Describe the result of executing the following:
MOV AL, 01010101B
AND AL, 00011111B (AL = 00010101B)
OR AL, 11000000B (AL = 11010101B)
XOR AL, 00001111B (AL = 11011010B)
NOT AL (AL = 00100101B)

Ans. AL = 00100101

Shift instructions

As its name implies, shift instructions are for shifting the bit(s) out of the operand. So
what will happen to the bit shifted out? What will happen to the vacated bit position?
There are 4 shift operations
Can perform: logical shift and arithmetic shift
Can shift left as well as right

Logical shift the vacated bit will be filled with 0 and the bit shifted out will be stored
in the Carry flag.
Arithmetic shift the vacated bit will be filled with the original most significant bit (this
only applies in right shift, in left shift vacated bit is filled with 0 as well.)

Arithmetic shift will maintain the sign of the original data


If shift more than 1 bit out then the number of shift operation to be performed is stored in
the CL register.
Shift operations are important because for a binary pattern, shifting 1-bit to the left is
equivalent to multiply the value by 2. For example, if the original value is 1, shifting 1
bit to the left, the value becomes 2!!!!

Original 0 0 0 0 0 0 0 1
Shifted 0 0 0 0 0 0 1 0
1 bit
left

On the other hand, shift to the right is the same as divide the value by 2. For example,
if the original value is 2 then shift to the right by 1 bit, the value becomes 1.
Shift operations can be used in multiply and divide operations.

Mnemonic Meaning Format Operation Flags affected


SAL/SHL Shift arithmetic SAL/SHL D, Shift the (D) left by the C, O depends on
left/shift logical left Count number of bit positions result
equal to count and fill
the vacated bits OF = 0 if first
positions on the right operand keeps
with zeros original sign
SHR Shift logical right SHR D, Count Shift the (D) right by C, O depends on
the number of bit result
positions equal to
count and fill the OF = 0 if first
vacated bits positions operand keeps
on the left with zeros original sign

SAR Shift arithmetic right SAR D, Count Shift the (D) right by C, O depends on
the number of bit result
positions equal to
count and fill the OF = 0 if first
vacated bits positions operand keeps
on the left with the original sign
original most
significant bit

Shift left

Bits being shifted

Shift Right

Example
Mov AL, 10001100b
MOV CL, #1
SHR AL, CL ; shift right 1 time

Result = 0100 0110 Carry = 0

Mov AL, 10001100b


Mov CL, #1
SAL AL, CL ; arithmetic shift right 1 time

Result 1100 0110b Carry = 0


The CL register holds the number of shift to be performed.

Rotate instructions

Rotate is similar to shift but the vacate bit is filled with the bit rotated out from the other
side.
Rotate left through carry (RCL) bit rotated out is stored in the carry flag, the vacated bit
is filled by the carry flag

Eg RCR BX, CL ; rotate right thro carry 4 times


If CL = 04H and BX = 1234H what is the result of the above operation?
The value of CL in the above example represents the number of the rotate operations.
So the rotate 4 times
1000 0001 0010 0011 if C is 0 at the beginning

Rotate left

Carry

Rotate left thro carry

OF=0 if first operand keeps original sign.

Rotate operations

Mnemonic Meaning Format Operation Flags


affected
ROL Rotate left ROL D, Count Rotate the D left by the C, O depends
number of bit positions on result
equal to Count. Each OF = 0 if first
bit shifted out from the operand keeps
leftmost bit goes back original sign
into the rightmost bit
position
ROR Rotate ROR D, Count Rotate the D right by C, O depends
Right the number of bit on result
positions equal to OF = 0 if first
Count. Each bit shifted operand keeps
out from the rightmost original sign
bit goes back into the
leftmost bit position
RCL Rotate left RCL D, Count Same as ROL except C, O depends
thro carry carry is attached to D on result
OF = 0 if first
for rotation operand keeps
original sign

RCR Rotate RCR D, Count Same as ROL except C, O depends


right thro carry is attached to D on result
carry for rotation OF = 0 if first
operand keeps
original sign

Exercise

1. How would the decimal number 1234 be coded in ASCII and stored in memory
starting at address 0C000H? Assume that least significant digit is stored at the lower
addressed memory location
Ans. 1 = (31H in 0C003H) 2 = (32H in 0C002H) 3 = (33H in 0C001H) 4 = (34H in
0C000H)

2. If register BX contains the value 0100H, register DI contains 0010 and register
DS contains 1075, what physical memory location is swapped when the following
instruction is executed
XCHG [BX+DI], AX
PA = 10750+0100+0010 = 10860H

3. Compute the physical address for the specified operand in each of the following
instructions:
MOV [DI], AX (destination operand) (0B000+0200 = 0B200)
MOV DI, [SI] (source operand) (0B000+0100 = 0B100)
MOV DI+XYZ, AH (destination operand) (0B000+0200+0400 = 0B600)
Given CS=0A00, DS=0B00, SI=0100, DI=0200, BX=0300, XYZ=0400
Assembly language programming III

Once you have gained the basic concept of assembly language programming, we can now
discuss more advanced topics including:
Flag control instructions
Compare and jump
Concept of subroutines
Loop and string instructions

Flag instructions

The flags are stored in a single register and a flag has only 2 status (set or clear).
When a flag is set, ie it is equal to 1; on the other hand, the flag is clear when it is 0.
The flag instructions allow programmers to manipulate the flag status directly. You can
set or clear a particular flag, or perform a complement (0->1, 1->0).

The instructions that can control the flags are given below:

Mnemonic Meaning Flags Affected

LAHF Load AH from flag None

SAHF Store AH into flags SF, ZF, AF, PF, CF

CLC Clear carry CF

STC Set carry CF

CMC Complement carry CF

CLI Clear interrupt IF

STI Set interrupt IF

The CLC, STC, and CMC are the most commonly used.

Compare instructions

Compare instructions are used when you need to make a branch or jump based on the
results after the comparison. In high-level programming, you have the IF, WHILE
statements.
In assembly language programming, when you perform a compare the overflow, sign,
zero, auxiliary carry, parity and the carry flag will be affected.
You can compare two 8-bit or two 16-bit values, and the operands can be stored in a
Register, memory, AX register or an immediate.

The compare instruction mnemonic is CMP and after the compare a branch or jump
instruction is usually followed according to the flags status.
When the compare operation is executed, the source operand is subtracted from the
destination operand. But the result of the subtraction is not saved (i.e. values in the source
and destination will not change)
Flags are changed according to the subtraction result and decision making is based on the
flags status.

Example

In C++, you can implement:


If (x => 100)

How this can be done using assembly language programming?

You can compare value of x and 100, after the compare operation, test the Carry
flag. If Carry flag is clear then x > 100 is true!!

Syntax of compare operation (CMP)


CMP 10011001, 00011011
Result for the compare is 01111110 (10011001 00011011)
Results of flags after the compare (you should validate the followings)
CF is clear
OF is set
SF is clear
ZF is clear

Exercise
Determine the status for flags (C, S, Z, O) as the following instructions are being
executed
MOV AX, 1234
MOV BX, 0ABCDH ; this is a 16-bit value
CMP AX, BX
Assume that initially all flags are clear

Branch and Jump instructions

Branch and jump instructions can alter the flow of the program, as shown below.

Normal program flow is top-down. However, the program flow can also be adjusted by
programming.
Program flow changed by a
Jmp A jump

A:

There are three kinds of jump and branch jmp, looping, and subroutine call.

Jump (jmp) after the jump, the program will execute instructions at the jump label
and will not return to the point where the jump is invoked.
Syntax: jmp label

Subroutine call (call) program will go to the location of the subroutine, execute the
subroutine and when it finishes return back to the original program
Syntax: call subroutine (or acall subroutine)

Jump instruction

The Jump instruction alters the execution path of instructions in the program by changing
the values of the code segment register (CS) and the instruction pointer (IP). In most
cases, only the IP value is changed.
Program execution is not intended to return to the next sequential instruction after the
jump, so no return information is saved.
Two kinds of jump operation: unconditional and conditional

Unconditional jump

As its name implies, there are no status requirements imposed for the jump to occur
When the instruction is executed, the jump always takes place to change the execution
sequence.
Conditional Jump

The jump operation depends on some status conditions (for example jump if Carry flag is
set!)
If condition(s) is/are met, then the jump takes place; otherwise execution continues
with the next sequential instruction of the program.

There are 2 kinds of unconditional jump: intrasegment jump, and intersegment jump
Intrasegment jump is limited to addresses within the current code segment (only the IP
value is changed)
Intersegment jump permits jumps from one code segment to another (both CS and IP
values are changed).

Examples for unconditional JUMP

JMP $ -14
Short-label an 8-bit number is coded as an immediate operand to specify a signed
displacement (+127 to 128)

JMP START
Near-label operand specifies a new value of IP with a 16-bit displacement
START is a label

Various addressing modes can also be used to specify a jump location

Example

XOR BX,BX ; why doing this ?????


Start: mov AX, 1
ADD AX,BX
JMP NEXT ; doing an unconditional jump with near label
NEXT: mov BX, AX
JMP start

Conditional JUMP

Conditional jump is based on some conditions. If the condition is satisfied then the jump
takes place otherwise, the instruction following the jump will be executed.

Conditions usually based on the flag status, eg Carry, Parity, Overflow

Some conditional jump mnemonic:

JC (Jump if Carry flag is set)


JS (Jump if Sign flag is set)
JB (jump if CF is set but must follow the CMP operation)
JNL (jump if first operand is not less than second operand ie SF = OF)

Example

The program that follows implements what is known as a delay loop

MOV CX, 1000


DLY: DEC CX ; decrement value of CX register CX = CX-1
JNZ DLY ; jump if not zero (zero is specified by which flag?)
; where is the jump point?
NXT: -----

How many times does the JNZ DLY get executed?


Change the program so that JNZ DLY is executed just 17 times

Exercise

A student has written a for loop using C++ program, how the loop can be implemented
with 8086 assembly language programming?

The original for loop is:

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

Stack operations

The stack (or the stack segment) is used as a temporary storage. But how can we put
data into the stack?

PUSH and POP are used to access the stack.


To put data into the stack, we do a PUSH.
To get data out, a POP is needed
Everytime, when we do a push a 16-bit data (2 bytes) is stored in the stack. Similarly a
16-bit data will be extracted when a POP is performed.

Syntax:
PUSH AX ; store data in the AX register onto to the stack
POP BX ; get data stored in the top of the stack and put it to the BX register

Data must be 16-bit so you can do PUSH AX but not PUSH AL!
The Stack is also a segment so it is also access via the segment (SS) and the offset SP
When data is getting in and out of the stack, the SP (Stack Pointer) is updated
accordingly. SP is the offset relative to the SS (Stack segment register). The initial value
of SP is FFFEH and when data is stored into the stack then the stack grows
downward, ie the SP value decreases.
When data is being extracted, or POP, from the stack, the SP value increases, or the
stack grows upward.
The SP always points to the Top of the Stack (TOS). The TOS refers to the location
holding the last data PUSHed into the stack.
The stack is a Last-in-first-out device. The last data pushed to the stack will be extracted
in the next POP operation.

When performing PUSH AX ; value of AH is stored in SP-1, value of AL is stored in SP-


2, the new value of SP is SP-2, ie the location of the last data.

During a POP operation, e.g. POP AX


Content of SP is stored in AL
Content of SP+1 is stored in AH
New value of SP is SP+2

We can also store contents of flag register into the stack by PUSHF and restore by POPF

Example

PUSH AX
PUSH BX
POP AX
POP BX

The above codes can exchange the value stored in AX and BX


Subrountines
A subroutine is a special segment of a program that can be invoked (called) for execution
from any point in a program (similar to a function in C++ program).
To invoke a subroutine, we perform a CALL
Using subroutines can reduce the size of the program and make the program easier to
read and understand.

When performing a CALL operation, value of IP is changed in order to branch to the


location of the subroutine. When the subroutine is completed then the program returns to
the main program so the last statement in the subroutine must be RETURN (RET).

There are intrasegment call (subroutine locates in the same code segment) and
intersegment call (subroutine locates in a different segment).

During a CALL operation, address for the instruction following the call instruction
(or the IP value) is stored in the STACK.
The IP value saved is the instruction following the CALL operation and this is very
important because when returning from a subroutine, we need to know what instruction
to be executed and this is by extracting the saved value from the stack!

Examples of different formats of subroutine call:

CALL ABC (where ABC is the name of a subroutine)


CALL 1234 (1234 is a 16-bit displacement that gets added to IP)
CALL BX (contents of BX are loaded into IP)
CALL WORD PTR [BX]
Offset address at the memory location whose physical address is derived from the
contents of DS and BX. The value stored at this memory location is loaded into IP. The
current contents of CS and the new value in IP point to the first instruction of the
subroutine

CALL FARPROC
Farproc (this is a intersegment call) represents a 32-bit immediate operand that is stored
in the 4 bytes that follow the opcode of the call instruction in program memory. These
two words are loaded directly from code segment memory into IP and CS

Mnemonic for RETURN is RET


During the return operation, value of IP or both the values of IP and CS that were saved
on the stack to be returned back to their corresponding registers. Once the IP is updated
then the program can go back to the program and continue to run.

Example

Write a procedure, or subroutine named SUM that adds 2 numbers 5 and 31 together and
places their sum in DX. Assume that this procedure is to be called from another
procedure in the same code segment and that at the time it is to be called, DX contains
the value of ABCD16 and this value must be saved at entry of the procedure and restored
at
its completion.

Sum proc near ; define the procedure or subroutine


push dx ; store value of dx register
mov dx, 5
add dx,31 ; dx = 5+31
pop dx ; restore original value of dx
ret ; return from subroutine
Sum endp

LOOP instructions

The Loop instruction provides a mechanism to repeat a sequence of operations repeatedly.


In C++, you have learnt the for statement, do while, and while.

Three different operations: loop, loope/loopz, and loopne/loopnz


The number of looping, or iterations, is stored in CX register.
Whenever LOOP is executed, the content of CX is first decremented by 1 and then
checked to determine if it is equal to 0. If CX equals to 0, then return to the instruction
following the loop statement

Syntax of the loop operation

mov cx, count


Next: ..

; statements performed in the loop

Loop Next ; CX is decremented and tested loop back to Next if CX !=0


Loop
repeated

Check CX
If CX != 0 then loop

Loop while equal (loope) checks the contents of both CX and the ZF flag. Each time the
loop instruction is executed, CX decrements by 1 without affecting the flags, its contents
are checked for 0, and the state of ZF that results from execution of the previous
instruction is also tested for.

Loope (loop if CX != 0 and ZF = 1)


The looping will continue if both CX not equal to 0 AND Zero flag is set.

Loopne (loop not equal) meaning is looping will continue when not equal!
Loopne (loop if CX != 0 and ZF = 0)

Exercise

Given the following sequence of instructions:


mov AX, 0
mov DS, AX
mov AL, 05
mov DI, A000
mov CX, 0FH ; this is a hex
Again: inc DI
cmp [DI], AL
loopne Again
Next:
Determine the value in the DI register when the program is at the label Next. What is the
purpose of the statement cmp [DI], AL ???

String instructions

String refers to a series of data words (characters) (or bytes) that reside in consecutive
memory locations.
You can move a string from a block of memory to a block elsewhere.
Can scan a string of data elements stored in memory looking for a specific value
Can also compare two strings

There are five basic string instructions

Basic string instructions

Mnemonic meaning Format

MOVS Move string MOVs operand

MOVSB Move string byte MOVSB


Movsw Move string word Movsw

Cmps Compare string Cmps operand

Scas Scan string Scas operand

Lods Load string Lods operand

Stos Store string Stos operand

The instructions MOVS, MOVSB, MOVSW all perform the same basic operation.
An element of the string specified by the source index (SI) register with respect to the
current data segment (DS) register is moved to the location specified by the destination
index (DI) register with respect to the current extra segment (ES) register.

The string operations can operate on a byte or a word.


After the move is completed, the contents of both SI and DI are automatically
incremented or decremented by 1 for byte move, or by 2 for word move
Before the operation MOVSB, the source string as well as the destination must be
addressed by the proper pointer. The operation MOVSB does not take any operands.

The Direction flag


Direction flag selects the auto-increment or the auto-decrement operation for the DI and
SI registers during string operations. The direction flag is used only with the string
instructions.

CLD clear direction flag (D=0 auto increment) (left to right)


STD set (D=1 auto decrement) (right to left)

Example, for a string abcdefgh is stored in the memory then the character a will be
stored at the lowest address and h will be stored at the highest address. So for auto
increment of addresses, we will process from a to h. While for auto-decrement, we
will process from h to a.

Example

Mov AX, datasegaddr ; load AX with data segment address


Mov DS, AX
Mov ES, AX
LEA SI, blk1addr ; note this is moving the address
LEA DI, blk2addr
Mov CX, N
CLD ; clear the direction flag - increment

Next: movsb ; no operand!!!


Loop Next
HLT ; halt

Compare strings

Compare operations perform: subtracts the destination operand from the source operand
and adjusts flags CF, PF, AF, ZF, SF, and OF accordingly.
The result of subtraction is not saved
Operation does not affect the operands

Example cmps byte ; compare string

Source is pointed to by the address in SI


Destination is specified by DI
SI and DI are updated after the operation and pointed to the next element

Scan string

AL, or AX stores a target element


Destination string is referred by DI and ES
Flags are adjusted based on the operation and DI incremented or decremented
Example: mov AX, 0
mov DS, AX
mov ES, AX
mov AL, 05H
mov DI, A000H
mov CX, 0F
CLD ; clear direction flag
Again: scasb ; scan byte
loopne again ; stop if find the same byte
Next:

Load and store string


To move string elements between the accumulator and memory
LODS loads either a byte or a word from a string in memory into AL or AX, respectively
Address is derived from SI and DS

Example LODS word

Load AX with a word


Value of SI is incremented by 2
STOS stores a byte from AL or a word from AX into a string location in memory
Location is generated by ES and DI

Example

mov AX, 0
mov DS, AX
mov ES, AX
mov AL, 05
mov DI, A000
mov CX, 0F
CLD
Again: stosb
loopne again
Next:

Result: store the value 5 into location A000 to A00F

Exercises
1. Refer to the following 8086 assembly language program, determine the contents of msg3 at the end of
the program, as well as the value of BL.

name "mycode" ; output file name (max 8 chars for DOS compatibility)
org 100h ; set location counter to 100h
lea si, msg
lea di, msg2
mov cx, 10
CLD
push si

next_char:
movsb
loop next_char

mov al, 'a'


pop DI
scan_char:
scasb
loopne scan_char

lea si, msg


lea di, msg3
mov bl, 0

cmp_char:
inc bl
cmpsb
loopnz cmp_char

ret ; return to the operating system.

msg db "Press any key!"


msg2 db ?
msg3 db "this is a test"

2. Refer to the following assembly program, and answer the following questions. Give proper
explanation to your answer.

#make_BIN#

; program begins here

MOV CX, 5 ; move


MOV AL, 0 ; move
MOV BX, 0 ; move

next:
ADD AL, V1[BX] ; add two values
MOV V1[BX], BL ; move
INC BX ; BX=BX+1
LOOP next ; loop back to next

MOV V2, AL ; move

HLT ; program ends

; variables:
V1 DB 24, 3, 2, 4, 1 ; just like an array
V2 DB 0

What is the value of BX at the end of the program?


What is the value of V2 at the end of the program?
What are the values stored in V1 at the end of the program?
What is the main purpose of the program?
If the variable V1 is now changed to V1 DB 12, -13, 20, 200, 37, -1. Can the program serve the
same purpose as before?

3. A student has written an assembly program to add data stored in an array called store. Where is
the sum stored in the current program? Now values stored in the array store become -12, 23, 18, 12, 58,
225. Modify the program so that it can now evaluate the average value of the 6 numbers.You must give
proper explanation for the modifications made. (Hints: You should consider the data size.)

#make_COM#
; com file is loaded at CS:0100h

ORG 100h
Jmp start
store db 23, 18, 12, 58
Start: ; program begins
LEA BX, store
mov CX, 4
Repeat: mov al, [bx]
add dl, al
add bx, 1
loop repeat
Finish: ; program terminates
RET
End

You might also like