academics.su.edu.krd · web viewthe define byte ,db, define word ,dw, and define double word ,dd,...

85
Microprocessor Assembly Language Programming For 2 nd class References 1- Abel P., "IBM PC Assembly Language and Programming", 4th Edition, Prentice Hall,1998.. 2- Thorne M., "Computer Organization and Assembly Language Programming", 2 nd Edition, Benjamin/Cummings, 1990. 3-“Microprocessors, PC Hardware and interfacing” by N.Mathivanan 4-The 8086 Microprocessors Architecture,software and Interfacing techniques By: Walter A. Triebel 5-The 8086/8088 MPU, Architecture,programming and interfacing BY: Barry B. Brey Grading: 1 st semester theory exam 12% 1 st semester practical exam 6% 2nd semester theory exam 12% 2nd semester practical exam 7% daily home works 3% 40% Final exam (Theory and Practical) 60% Objective : Understand fundamental concepts of 8086 Microprocessor architecture. 1

Upload: others

Post on 25-Jul-2021

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Microprocessor

Assembly Language Programming

For 2nd class

References

1- Abel P., "IBM PC Assembly Language and Programming", 4th Edition, Prentice Hall,1998..2- Thorne M., "Computer Organization and Assembly Language Programming", 2nd Edition, Benjamin/Cummings, 1990.3-“Microprocessors, PC Hardware and interfacing” by N.Mathivanan4-The 8086 Microprocessors Architecture,software and Interfacing techniquesBy: Walter A. Triebel5-The 8086/8088 MPU, Architecture,programming and interfacingBY: Barry B. Brey

Grading:

1st semester theory exam 12%

1st semester practical exam 6%

2nd semester theory exam 12%

2nd semester practical exam 7%

daily home works 3%

40%

Final exam (Theory and Practical) 60%

Objective:

Understand fundamental concepts of 8086 Microprocessor architecture. Studying assembly language 8086 instruction set and addressing mode. Solve common problems using assembly language

1

Page 2: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

High Level and Law Level languagesMachine code is the only form of program instructions that the computer hardware can understand and execute directly. All other forms of computer language must be translated into machine code in order to be executed by the hardware. Machine code consists of many strings of binary digits that are easy for the computer to interpret, but boring for human beings to interpret. Machine code is different for each type of computer. A program in machine code for an Intel x86-based PC will not run on an IBM mainframe computer, and vice versa.

Assembly language is a symbolic representation of machine code, which allows programmers to write programs in machine code without having to deal with the long binary strings. For example, the machine code for an instruction that adds two numbers might be 01101110, but in assembly language, this can be represented by the symbol ADD. A simple assembler program translates this symbolic language directly into machine code. Because machine code is specific to each type of computer hardware, assembly languages are also specific to each type of computer. However, all machine languages and assembly languages look very similar, even though they are not interchangeable.

High-level language is a language that is convenient for human beings to understand. High-level programming languages must be translated into machine code for execution, and this process is called compilation. A program that carries out this translation is a compiler. High-level language may bear no resemblance at all to machine code. The compiler figures out how to generate machine language that does exactly what the high-level-language source program specifies. Languages like C++, Algol, COBOL, etc., are all compiled high-level languages. They usually work more or less the same across all computer types, which makes them much more portable than assembly language.

Some high-level languages are interpreted rather than compiled. This means that they are not translated into machine code. Instead, when the program is executed, another program, called an interpreter, looks at the source code and does what it says, without actually translating it into machine language. Visual Basic, Java, Javascript, BASIC, and many other languages work this way. It's more flexible, but it is far slower than a compiled language.

Example: A function in 32-bit x86 machine code to calculate the nth Fibonacci number:

8B542408 83FA0077 06B80000 0000C383FA027706 B8010000 00C353BB 01000000

B9010000 008D0419 83FA0376 078BD98B

into assembly code.2

Page 3: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Example: The same Fibonacci number calculator as above, but in x86 assembly language using MASM syntax:

fib: mov edx, [esp+8] cmp edx, 0 ja @f mov eax, 0 ret @@: cmp edx, 2 ja @f mov eax, 1 ret @@: push ebx mov ebx, 1 mov ecx, 1 @@: lea eax, [ebx+ecx] cmp edx, 3 jbe @f mov ebx, ecx mov ecx, eax dec edx jmp @b @@: pop ebx ret

C84AEBF1 5BC3

3

Page 4: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Input

ALU Register Array Control

Microprocessor Output

System bus

ROM R/WM

Memory

Microcomputer Architecture

• A computer system has three main components: a Central Processing Unit (CPU) or processor, a Memory Unit and Input Output Units (devices). In any microcomputer system, the component which actually processes data is entirely contained on a single chip called Microprocessor (MPU). This MPU can be programmed using assembly language. Writing a program in assembly language requires a knowledge of the computer hardware (or Architecture) and the details of its instruction set.

• The main internal hardware features of a computer are the processor, memory and registers (registers are special processor components for holding address and data).

• The external hardware features are the computer Input/Output devices such as keyboard, monitor…

Software consists of the operating system (O.S) and various programs and data files.

CPU function:

The CPU is divided into two general parts. Arithmetic Logic Unit(ALU) and Control Unit (CU).- The ALU carry Arithmetic, logical, and shifting operations.- The CU fetches data and instruction, and decodes addresses for the ALU. The function of the control unit is to provide timing signals for synchronizing the transfer of data between the CPU and peripheral devices, including memory, through a group of wires known as the system bus

Figure(1):block diagram of a microcomputer

System Bus

• The components of the computer system must communicate with each other and with the outside world. The processor is connected to memory and all peripherals using a bus.

• A Bus is a bunch of wires, and electrical path on the printed IC to which everything in the system is connected.

4

Page 5: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

There are three types of Bus:

Address Buss : for carrying the address/location of the memory where the data has to be placed.

Data Bus : for carrying the data/ information between micro processor and I/O device.

Control Bus : for carrying the timing and control signals, typical control signals includes memory read, memory write, I/O read, I/O write, interrupt acknowledge, bus request. These control signals indicates the type of action taking place on the system bus.

Personal Computer (PC) Components

• The main component of the PC is its System Board (or mother board). It contains the processor, co-processor, main memory, connectors, and expansion slots for optional cards.

• The slots and connectors provide access to such components as ROM, RAM, hard disk, CD-ROM drive, additional memory, video unit, keyboard, mouse, parallel and serial device, sound adapter and cache memory (the processor use high speed cache memory to decrease its need to access the slower main memory). A bus with wires attached to the system board connects the components. It transfers data between the processor, memory and external devices

The processor

• The CPU or processor acts as the controller of all actions or services provided by the system. The operations of a CPU can be reduced to three basic steps: fetch, decode, and execute. Each step includes intermediate steps, some of which are:

1- Fetch the next instruction:

- Place it in a holding area called a queue.

2- Decode the instruction

- Perform address translation.

- Fetch operand from memory.

3- Execute the instruction.

- Perform the required calculation.

- Store results in memory or register.

5

Page 6: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

220−1

2

1

8085 /8086MPU

D8D0

InputMemory

Output

20 bit Address busbus

Real word

16bit Data bus

Control bus

General organization of microcomputer

Figure (2) 8085/8086 Bus Structure

B. MemoryThe memory of a computer system consist of tiny electronic switches, with each switch set in one of two states: open or close. It is however more convenient to think of these states as 0 and 1.

Thus each switch can represent a binary digit or bit, as it is known, the memory unit consists of millions of such bits, bits are organized into groups of eight bits called byte.8086 can address up to 1 MB (220 bytes) of main memory this magic number comes from the fact that the address bus of the 8086 has 20 address lines.

Fig(3): logical view of the system memory

Address in Decimal Address in Hex

6

FFFFF

FFFFE

00002

00001

00000

Page 7: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

. . .

Two basic memory operationsThe memory unit supports two fundamental operations: Read and Write. The read operation read a previously stored data and the write operation stores a value in memory. See Figure 4

Address Data

Read

Write

Fig(4) : block diagram of system memory

Steps in a typical read cycle:1- Place the address of the location to be read on the address bus.2- Activate the memory read control signal on the control bus.3- Wait for the memory to retrieve the data from the address memory location.4- Read the data from the data bus.5- Drop the memory read control signal to terminate the read cycle.

Steps in a typical write cycle:1- Place the address of the location to be written on the address bus.2- Place the data to be written on the data bus.

3- Activate the memory write control signal on the control bus.

4- Wait for the memory to store the data at the address location..5- Drop the memory write control signal to terminate the write cycle.

Addresses: group of bits which are arranged sequentially in memory, to enable direct access, a number called address is associated with each group. Addresses start at 0 and increase for successive groups. The term location refers to a group of bits with a unique address. Table 1 represents Bit, Byte, and Larger units.

Name Number of ByteBit 0 or 1Byte Is a group of bits used to represent a character, typically 8-

7

Memory Unit

Page 8: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

bit.Word 2 byte (16 bit)data itemDouble Word 4 byte (32 bit)QuadWord 8 byte (64 bit)Paragraph 16 byte (128 bit)kilobyte (KB) 2^10=1024=1K for kilobyte, thus 640K=640*1024=655360

bytes

Evolution of Intel MicroprocessorThe principle way in which MPU & microcomputer are categorized in term of the maximum number of binary bit in the data they process that is, their word length. Processor vary in theirspeed, capacity of memory, register and data bus, below are a brief description of various Intel processor in Table 2. 8088 and 8086 functionally identical but 8088 lower performance, 80186 run all 8088 and 8086 software, but have 10 new instructions. 80188 in function is identical to 80186 but lower performance. 80286 run all 8086, 80186 program, but has extra instruction, more powerful than 8086. 83086 has various operationmode, which allow it to act as 80286 chip or multiple 8086 chip, as well as a set of instruction capable of 32 bit operations such as arithmetic instructions.

MicroprocessorName

Features DescriptionsWidth of(DataBus)

Width of(AdressBus)

InstructionQueue length

8086 16 bit 20 bit 6 Byte8080 8 bit 20 bit 4 Byte80186 16 bit 20 bit 6 Byte80188 8 bit 20 bit 4 Byte80286 16 bit 24 bit 6 Byte80386 32 bit 32 bit 6 Byte

Table 2: Different Microprocessor features descriptions

Types of memoryThe memory unit can be implemented using a variety of memory chips- different speeds, different manufacturing technology, and different sizes. The two basic types are RAM and ROM.

8

Page 9: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

1- Read Only Memories (ROM):ROMs allow only read operation to be performed. This memory is non-volatile. Most ROMs are programmed and cannot be altered. This type of ROM is cheaper to manufacture than other types of ROM. The program that controls the standard I/O functions (called BIOS) is kept in ROM, configuration software.

Other types of ROM include:- Programmable ROM (PROM).- Erasable PROM (EPROM) is read only memory that can be reprogrammed using special equipment.- EAPROM, Electrically Alterable Programmable ROM is a Read Only Memory that is electrically reprogrammable.

2- Read/Write MemoryRead/Write memory is commonly referred to as Random Access Memory (RAM), it is divided into static and dynamic. Static RAM (SRAM): used for implementing CPU registers and used for special high speed memory called cache memory which greatly improves system performance. Static RAM keeps its value without having to be refreshed.Dynamic RAM (DRAM): main memory, or RAM is where program, data are kept when a program is running. It must be refreshed with in less than a millisecond or losses its contents.INPUT/OUTPUTInput/Output (I/O) devices provide the means by which the computer system can interact with the outside world. Computers use I/O devices (also called peripheral devices) for two major purposes:1- To communicate with the outside world and,2- Store data.Devices that are used to communicate like, printer, keyboard, modem, Devices that are used to store data like disk drive. I/O devices are connected to the system bus through I/O controller (interface) – which acts as interface between the system bus and I/O devices.

There are two main reasons for using I/O controllers1- If I/O devices are connected directly, the CPU would have to understand and respond appropriately to each I/O device. This would cause the CPU to spend a lot of time interacting with I/O devices and spend less time executing user programs.2- The amount of electrical power used to send signals on the system bus is very low. This means that the cable connecting the I/O device has to be very short (a few centimeters at most). I/O controllers typically contain driver hardware to send current over long cable that connects I/O devices.

Execution Unit and Bus Interface UnitThe processor is partitioned into two logical units: an Execution Unit (EU) and Bus Interface Unit (BIU). The role of the EU is to execute instruction, whereas the BIU delivers instruction and data to EU. The EU contains ALU, CU and number of registers. This feature enables the EU to execute instructions and perform arithmetic and logical operations.The most important function of BIU is to manage the bus control unit, segment registers instruction queue. The BIU controls the busses that transfer data to

9

Page 10: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

123:

Bus Controlunit

NIP

InstructionQueue

the EU, to memory, and to external input/output devices, whereas the segment registers control the memory addressing.

Program control

AH AL

BH BL

CH CL

DH DL

SP

BP

SI

DI

ALU

CU

Flag

Exection Unit Bus Interface Unit

Figure 6: Execution unit and Bus interface unit.

Another function of the BIU is to provide access to instructions. This feature enables the BIU to look ahead and prefetch instructions, so that there is always a queue of instructions ready to execute.

10

CS

DS

SS

ES

Page 11: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Most Significant Byte

The EU and BIU work in parallel, with the BIU keeping one step ahead. The EU notifies the BIU when it needs access to data in memory or I/O devices. Also the EU request machine code instructions from the BIU instruction queue. The top instruction is the currently executable one, and while the EU is occupied executing an instruction, the BIU fetch another instruction from memory. This fetching overlaps with execution is called pipelining and it speeds up processing.

Addressing Data in MemoryDepending on the model, the processor can access one or more bytes of memory at a time. Consider the Hexa value (0529H) which requires two bytes or one word of memory. It consist of high order (most significant) byte 05 and a low order (least significant) byte 29.The processor store the data in memory in reverse byte sequence i.e. the low order byte in the low memory address and the high order byte in the high memory address. For example, the processor transfer the value 0529H from a register into memory address 04A26 H and 04A27H like this:

Register

Memory

The processor expects numeric data in memory to be in reverse byte sequence and processes the data accordingly, again reverses the bytes, restoring them to correctly in the register as hexa 0529H. When programming in assembly language, you have to distinguish between the address of a memory location and its contents. In the above example the content of address 04A26H is 29, and the content of address 04A27H is 05.There are two types of addressing schemes:1. An Absolute Address, such as 04A26H, is a 20 bit value that directly references a specific location. 2. ASegment Offset Address, combines the starting address ofa segment with an offset value.

Segments and AddressingSegments are special area defined in a program for containing the code, the data, and the stack. Segment Offset within a program, all memory locations within a segment are relative to the segment starting address. The distance in bytes from the segment address to another location within the segment is expressed as an offset (or displacement). To reference any memory location in a segment, the processor combine the segment address in a segment register with the offset value of that location, that is, its distance in byte from the start of the segment.

Specifying addressesTo represent a segment address and its relative offset we use the notation:Segment: offsetThus 020A:1BCD denotes offset 1BCDH from segment 020AH. The actual address it refers to is obtained in the following way:1- Add zero to the right hand side of the segment address.2- Add to this the offset.

11

Least Significant Byte

05 29FFFFF::04A28

04A27

04A26:00000

0529

Page 12: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Hence the actual address referred to by 020A:1BCD is 03C6D. Address Bus in the 8086 is 20 bits wide (20 lines) i.e. the processor can access memory of size 220 or 1048576 bytes (1MB).

Instruction Pointer = 16 bit register which means the processor can only address 0 – 216 (65535) bytes of memory. But we need to write instructions in any of the 1MB of memory. This can be solved by using memory segmentation, where each segment register is 16-bit (this 16-bit is the high 16-bit of Address Bus (A4- A19)) i.e. each of the segment registers represent the actual address after shifting the address 4-bit to get 20 bits.

Registers Registers are 8, 16, or 32-bit high speed storage locations directly inside the CPU, designed to be accessed at much higher speed than conventional memory. The CPU has an internal data bus that is generally twice as wide asits external data bus. Data Registers: The general purpose registers, are used for arithmetic and data movement. Each register can be addressed as either 16-bit or 8 bit value. Example, AX register is a 16-bit register, its upper 8-bit is called AH, and its lower 8-bit is called AL. Bit 0 in AL corresponds to bit 0 in AX and bit 0 in AH corresponds to bit 8 in AX. See Figure 8.

H L

8 15 7 0

AX Accumulator

AH AL

BX Base

BH BL

CX Count

DX Data

DH DL

Figure 8: General Purpose data registers

Instructions can address either 16-bit data register as AX, BX, CX, and DX or 8-bit register as AL, AH, BL, BH, CL, CH, Dl, and DH. If we move 126FH to AX then AL would immediately contain 6FH and AH = 12H.* Each general purpose register has special attributes:1- AX (Accumulator): AX is the accumulator register because it is favored by the CPU for arithmetic operations. Other operations are also slightly more efficient when performed using AX.

12

FFFF

Memory=1MB

FF

0000 0000

Only 64 Kb can

be used by IP since it is 16 bit

Page 13: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Direction

InterruptTrace

Auxiliary Cary

Overflow

Sign

Zero

Parity

Carry

= used

2- BX (Base): the BX register can hold the address of a procedure or variable. Three other registers with this ability are SI, DI and BP. The BX register can also perform arithmetic and data movement.3- CX (Counter): the CX register acts as a counter for repeating or looping instructions. These instructions automatically repeat and decrement CX.4- DX (Data): the DX register has a special role in multiply and divide operation. When multiplying for example DX hold the high 16 bit of the product.

* Segment Registers: the CPU contain four segment registers, used as base location for program instruction, and for the stack.1- CS (Code Segment): The code segment register holds the base location of all executable instructions (code) in a program.2- DS (Data Segment): the data segment register is the default base location for variables. The CPU calculates their location using the segment value in DS.3- SS (Stack Segment): the stack segment register contain the base location of the stack.4- ES (Extra Segment): The extra segment register is an additional base location for memory variables.

* Index registers: index registers contain the offset of data and instructions. The term offset refers to the distance of a variable, label, or instruction from its base segment. The index registers are:1- BP (Base Pointer): the BP register contain an assumed offset from the stack segment register, as does the stack pointer. The base pointer register is often used by a subroutine to locate variables that were passed on the stack by a calling program.2- SP (Stack Pointer): the stack pointer register contain the offset of the top of the stack. The stack pointer and the stack segment register combine to form the complete address of thetop of the stack.3- SI (Source Index): This register takes its name from the string movement instruction, in which the source string is pointed to by the source index register.4- DI (Destination Index): the DI register acts as the destination for string movement instruction.

Status and Control register:1- IP (Instruction Pointer): The instruction pointer register always contain the offset of the next instruction to be executed within the current code segment. The instruction pointer and the code segment register combine to form the complete address of the next instruction.2- The Flag Register: is a special register with individual bit positions assigned to show the status of the CPU or the result of arithmetic operations. The Figure9 describe the 8086/8088flags register:

13

Page 14: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Figure 9 : 8088 / 8086 Flag register

There two basic types of flags: (control flags and status flags)1- Control Flags: individual bits can be set in the flag register by the programmer to control the CPU operation , these are - The Direction Flag (DF): affects block data transfer instructions, such as MOVS, CMPS, SCAS. The flag values are 0 = up and 1 = down.- The Interrupt flag (IF): dictates whether or not a system interrupt can occur. Such as keyboard, disk drive, and the system clock timer. A program will sometimes briefly disable the interrupt when performing a critical operation that cannot be interrupted. The flag values are 1= enable, 0 = disable.- The Trap flag (TF): Determine whether or not the CPU is halted after each instruction. When this is set, a debugging program can let a programmer to enter single stepping (trace) through a program one instruction at a time. The flag values are 1 = on, 0 = off. The flag can be set by INT 3 instruction.2- Status Flags: The status flags reflect the outcomes of arithmetic and logical operations performed by the CPU, these are:- The Carry Flag (CF): is set when the result of an unsigned arithmetic operation is too large to fit into the destination for example, if the sum of 71 and 99 where stored in the 8-bit register AL, the result cause the carry flag to be 1. The flag values = 1 = carry, 0 = no carry.- The Overflow (OF): is set when the result of a signed arithmetic operation is too wide (too many bits) to fit into destination. 1 = overflow, 0 = no overflow.- Sign Flag (SF): is set when the result of an arithmetic of logical operation generates a negative result, 1= negative, 0 = positive.- Zero Flag (ZF): is set when the result of an arithmetic of logical operation generates a result of zero, the flag is used primarily by jump or loop instructions to allow branching to a new location in a program based on the comparison of two values. The flag value = 1 = zero, & 0 = not zero.- Auxiliary Flag: is set when an operation causes a carry from bit 3 to bit 4 (or borrow from bit 4 to bit 3) of an operand. The flag value = 1 = carry, 0 = no carry.- Parity Flag: reflect the number of 1 bits in the result of an operation. If there is an even number of bit, the parity is even. If there is an odd number of bits, parity is odd. This flag is used by the OS to verify memory integrity and by communication software to verify thecorrect transmission of data.

Number of OperandsOperands specify the value an instruction is to operate on, and where the result is to be stored. Instruction sets are classified by the number of operands used. An instruction may have no, one,two, or three operands. 1. three-Operand instruction:In instruction that have three operands, one of the operand specifies the destination as an address where the result is to be saved. The other two operands specify the source either as addresses of memory location or constants.EX1: A=B+CADD destination, source1, source2ADD A,B,CEX2:Y=(X+D)* (N+1)ADD T1, X, DADD T2, N, 1Mul Y, T1, T2

2. Two operand instruction

14

Page 15: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

In this type both operands specify sources. The first operand also specifies the destination address after the result is to be saved. The first operand must be an address in memory, but the second may be an address or a constant.ADD destination, sourceEX1: A=B+CMOV A, BADD A, CEX2: Y=(X+D)* (N+1)MOV T1, XADD T1, DMOV Y, NADD Y, 1MUL Y, T1

3. One Operand instructionSome computer have only one general purpose register, usually called on Acc. It is implied as one of the source operands and the destination operand in memory instruction the other source operand is specified in the instruction as location in memory.ADD source ,LDA source; copy value from memory to ACC., STA destination; copy value from Acc into memory.EX1: EX2:A=B+C Y=(X+D)* (N+1)LDA B LDA XADD C ADD DSTA A STA T1

LDA NADD 1MUL T1STA Y

4. Zero Operand instructionSome computers have arithmetic instruction in which all operands are implied, these zero operand instruction use a stack, a stack is a list structure in which all insertion and deletion occur at one end, the element on a stack may be removed only in the reverse of the order in which they were entered. The process of inserting an itemis called Pushing, removing an item is called Popping.

Computers that use Zero operand instruction for arithmetic operations also use one operand PUSH and POP instruction to copy value between memory and the stack.PUSH source; Push the value of the memory operand onto the Top of the stack.POP destination; POP value from the Top of the stack and copy it into the memory operand.

EX: EX:A=B+C Y=(X+D)* (N+1)PUSH B PUSH XPUSH C PUSH DADD; ADDPOP A PUSH N

PUSH 1ADDMULPOP Y

15

pop the two value of stuck, add them and

Page 16: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

0000

0100

IP

CS

XXXX

ABCD

Ax

BX

B8

C3

XX

01000

01001

01002

Before

memory address instruction

Mov AX, BX

Next Instruction

* Addressing Modes Of The 8088 / 8086

When the microprocessor executes an instruction , it performs the specified functions on these data are called its operands and may be part of the instruction reside in one of the internal registers of the 8088/8086 , stored at an address in memory or at an I/O Port.

To access these different types of operands the 8088/ 8086 is provided with various addressing modes , there is nine modes of addressing mode , of these modes , all but register addressing , port addressing and immediate addressing make reference to an operand stored in memory. Therefore , they require the Microprocessor to initiate a read or write of memory . the addressing provide different ways of computing the address of an operand . let us consider in detail each of these addressing modes :

1. Register Addressing Mode : with the register addressing mode , the operand to be accessed is specified residing in an internal register of the 8088 / 8068 . An example of an instruction that this addressing mode is :

MOV AX , BX

This stands for move the contents of B , the source operand , to AX the destination operand . Both the source and destination operands have been specified as contents of internal registers of the 8088 / 8086 .

Let us now look at the effect of executing the register addressing mode move instruction in figure 14-a , figure 14-b , where we see the state of MP before and after executing the instruction .

figure14_a , register addressing before execution

as we see ib the figure 14-a the state of MP before to fetching the instruction . Notice that IP and CS point to the MOV AX,BX instruction at address 01000H . before to execution of this instruction , the contents of BX are ABCDh and the AX represent a don’t care stat. As shown in Fig 14-b the result of executing the instruction is that ABCDh is coped into AX .

16

Page 17: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

0002

0100

IP

CS

ABCD

ABCD

Ax

BX

B8

C3

XX

01000

01001

01002

After

memory address instruction

Mov AX, BX

Next Instruction

0000

0100

IP

CS

Ax

BX

B0

15

XX

01000

01001

01002

Before

memory address instruction

Mov Al, 15h

Next Instruction

XXXX 01003

Figure10_b , register addressing after execution

2. Immediate Addressing Mode: If the source operand is part of the instruction instead of the contents of a register or memory location , it represents what is called an Immediate operand and is accessed using the immediate addressing mode . typically , immediate operands represent constant data.

Immediate operands can be either a byte or word of data . In the instruction Mov AL , 15H the source operand 16h is an example of a byte-wide immediate source operand, Note that the value of the immediate operand must always begin with one of the numbers 0 through 9 . For example , if the immediate operand is to be A5h it must be written as 0A5h . The destination operand , which is the contents of AL uses register addressing . thus this instruction employs both the immediate and register addressing modes .

Figure 11-a And 11-b illustrates execution of this instruction . Here we find that the immediate operand 15h is stored in the code segment of memory in byte location immediately following the opcode of the instruction . this value fetched , along with the opcode for MOV , into the instruction queue within the MP .when it performs the move operation , the source operand is fetched from the instruction queue and not from the memory , and no external memory operation are performed . Notice that the result produced by executing this instruction that the immediate operand , which equals 15h , is loaded into the lower-byte of the accumulator(AL) .

17

Page 18: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

0002

0100

IP

CS

Ax

BX

B0

15

XX

01000

01001

01002

After

memory address instruction

Mov Al, 15h

Next Instruction

15XX 01003

01004

01003

01002

0000

0100

IP

CS

XXXX

AX

BX

34

12

XX

01000

01001

memory address instruction

Mov CX , BETA

Next Instruction

XX

0200DS

CXXX

DXED

0E

8B

Source operand

02000

02001

03234

figure 11-a immediate addressing mode before execution instruction

figure 11-b immediate addressing mode After execution instruction

3. Direct Addressing Mode :Direct addressing differs from immediate in that the locations following the instruction opcode hold an effective memory address (EA) instead of data . The effective address is the 16-bit offset of the storage location of the operand from the location specified by the current value EA is combined with the contents of DS in the 8088/8086 to produce the physical address of the operand in memory . An example of an instruction that uses direct addressing for its source operand is : MOV CX , BETA

This stands for "move the contents of the memory location , which is label BETA in the current segment , into internal register CX ". The MP computes the offset of BETA From the beginning of the data segment and enter it as apart the instruction's machine code.

In figure 12-a we find that the value of the offset is stored in the two locations that follow the instruction . This value is also as the displacement . Notice that the value assigned to constant BETA is 1234h . As the instruction executed , the MP combines 1234h with 0200h to get the physical address of the source operand . this gives :

PA = 02000h + 1234h

= 03234h

Then it reads the word of data starting at this address , which is BEEDh , and loads it into the CX register . This result is illustrated in figure 12-b .

18

Page 19: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

03235

03234

02001

02000

01004

01003

01002

0004

0100

IP

CS

BEED

AX

BX

34

12

XX

01000

01001

memory address instruction

Mov CX , BETA

Next Instruction

XX

0200DS

CXXX

DXED

BE

0E

8B

Source operand

figure 12-a Direct addressing mode instruction before execution instruction

figure 12-b Direct addressing mode instruction after execution instructio

4. Register Indirect Addressing Mode : Register indirect addressing is similar to the direct addressing we just described in that an effective address is combined with the contents of DS to obtain a physical address . however , it differs in the way the offset is specified . this time EA resides in either a base register or an index register within the MP .The base register can be either base register BX or base pointer register BP , and the index register can be source index register SI or destination index register DI.

An example of an instruction that uses register indirect addressing is : MOV AX, [SI] this instruction moves the contents of the memory location offset by the value of EA in SI from the beginning of the current data segment to the AX register .

For instance , as shown in figure 13-a and 13-b if SI contains 1234h , and DS contains 0200h , the result produced by executing the instruction is that the contents of memory location :

PA = 02000h + 1234h = 03234h

19

Page 20: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Next Instruction

01004

01003

01002

0000

0100

IP

CS

AX

BX

xx

01000

01001

memory address instruction

Mov AX , [SI]

XX

0200DS

XXXX

CXXX

DXED

BE

04

8B

Source operand

02000

02001

03234

032351234SI

Next Instruction

01004

01003

01002

0002

0100

IP

CS

AX

BX

xx

01000

01001

memory address instruction

Mov AX , [SI]

XX

0200DS

BEED

CXXX

DXED

BE

04

8B

Source operand

02000

02001

03234

032351234SI

figure 13-a instruction using register indirect addressing before execution

Are moved to the AX register . Notice in figure 13-b that this value is BEEDh . In this example , the value 1234h that was found in the SI register must have been loaded with another instruction prior to executing this instruction and the example for the direct addressing mode are the same . however , they differ in the way in which the physical address was generated . the direct addressing method lends itself to applications where the value of EA is a constant . on the other hand. Register indirect addressing can be used when the value of EA is calculated and stored , for example , in SI by a previous . that is EA is a variable .

20

Page 21: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Next Instruction 01004

01003

01002

0000

0100

IP

CS

AX

BX

34

12xx

01000

01001

memory address instruction

Mov [BX] + BETA , AL

XX

DS

BE ED

CXXX

DXxx

xx

07

88

Destination operand

02000

02001

03234

03235

0200

1000

figure 13-b instruction using register indirect addressing after execution

5. Based Addressing Mode : In The Based addressing mode , the physical address of the operand is obtained by adding a direct or indirect displacement to the contents of either base register BX or base pointer register BP and the current value in DS or SS , respectively . A Move instruction that uses base addressing to specify the location of its destination operand is as follows :

MOV [BX] +BETA Or DISP , AL

This instruction uses base register BX and direct displacement BETA to derive the EA of the destination operand . the based addressing mode is implemented by specifying the base register in brackets followed by a + sign and the direct displacement . the source operand In this example is located in byte accumulator AL as shown in Fig . 14.a and 14.b , the fetch and execution of this instruction causes the MP to calculate the physical address of the destination operand from the contents of DS , BX ,and the direct displacement . the result is :

PA= 02000h +1000H+1234H = 04234H

Then it writes the contents of source operand AL into the storage location at 04234h . The result is that EDh is written into the destination memory location .

If BP is used instead of BX , the calculation of the physical address is performed using the contents of the stack segment (SS) register instead of DS . this permits access to data in the stack segment of memory.

21

Page 22: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Next Instruction 01004

01003

01002

0004

0100

IP

CS

AX

BX

34

12xx

01000

01001

memory address instruction

Mov [BX] + BETA , AL

XX

DS

B E ED

CXXX

DXED

xx

07

88

02000

02001

03234

03235

0200

1000

memory address instruction

14.a instruction using direct base pointer addressing before execution

14.b instruction using direct base pointer addressing after execution

6. Index Addressing Mode : indexed addressing works identically to the based addressing we just described , however , it uses the contains of one of the index registers , instead of BX or BP . in the generation of the physical address . here is an example :

MOV AL, [SI] + ARRAY

The Source operand has been specified using direct indexed addressing .Notice that the notation this time is such that ARRAY , which is a direct displacement , is added to the selected index register , SI . just like for the base register in based addressing , the index register is enclosed in brackets . the effective address is calculated as :

EA = (SI) + ARRAY

And the physical address is obtained by combining the contents of DS with EA . The example in the figure 15.a and 15.b shows the result of executing the MOV instruction . first the physical address of the source operand is calculated from DS , SI , and the direct displacement .

PA = 0200H + 2000 + 1234H = 05234h

Then the byte of data stored at this location , which is BEh , is read into the lower byte (AL) of the accumulator register

22

Page 23: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Next Instruction 01004

01003

01002

0004

0100

IP

CS

AX

34

12

xx

01000

01001

memory address instruction

Mov AL ,[SI] +ARRAY

DS

XX BE

44

8A

0200

2000SI

15.a instruction using direct indexed addressing before execution

23

Page 24: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Mov AH ,[BX] [SI] +BETA

BXXX

CX

XX

DX

BE Source operand

02000

02001

05234

Next Instruction 01004

01003

01002

0000

0100

IP

CS

AX

BX

34

12xx

01000

01001

memory address instruction

Mov AH ,[BX] [SI] +BETA AL

XX

DS

XX XX

CXXX

DXBE

xx

20

8A

Source operand

02000

02001

06234

0200

1000

2000SI

15.b instruction using direct indexed addressing after execution

7-Based Index Addressing Mode : combining the based addressing mode and the indexed addressing mode together results in a new , more powerful mode known as based indexed addressing . Let us consider an example of MOV instruction using this type of addressing .

MOV AH , [BX] [SI] +BETA

Notice that the source operand is accessed using based indexed addressing mode , therefore , the effective address of the source operand is obtained as :

EA = ( BX ) + ( SI ) + BETA

And the physical address of the operand from the current DS and the calculated EA . An example of executing this instruction is illustrated in Figure 16.a and 16.b . the address of the source operand is calculated as :

PA = 02000h + 1000h + 2000h +1234h = 6234h

Execution of the instruction causes the value stored at this location to be read into AH .

16.a instruction using based indexed addressing before execution

24

Page 25: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

xx

Next Instruction

01004

01003

01002

0004

0100

IP

CS

AX

BX

34

12

xx

01000

01001

memory address instruction

XX

DS

BE XX

CX

XX

DX

BE

20

8A

Source operand

02000

02001

06234

0200

1000

2000SI

16.b instruction using based indexed addressing after execution

8-String Addressing Mode :The string instructions of the 8088 , 8086 instruction set automatically use the source and destination index registers to specify the effective addresses of the source and destination operands , respectively . the move string instruction MOVS is an example . notice that neither SI nor DI appears in the description of the move string instruction , but both are used during its execution . in this mode of addressing the (PA) is specified by DS ,ES ,SI ,DI

MOVSB Copy byte at DS:[SI] to ES:[DI]. Update SI and DI.

Algorithm:

* ES:[DI] = DS:[SI]

* if DF = 0 then

o SI = SI + 1

o DI = DI + 1

else

o SI = SI - 125

Page 26: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

o DI = DI - 1

MOVSW copy word at DS:[SI] to ES:[DI]. Update SI and DI.

9-Port Addressing Mode: port addressing is used in 8086, IN and OUT instructions to access input and output ports . for ports in the I/O address space . only the direct addressing mode and an indirect addressing mode using DX are available . for example , direct addressing of an input port is used in the instruction IN AL , 15h

this stands for " input the data from the byte-wide input port at address 15h of the I/O address space to register AL "

another example Using indirect port addressing for the source operand in an IN instruction , we get IN AL , DX

It means " input the data from the byte-wide input port whose address is specified by the contents of the register DX " .

IN Input from port into AL or AX. Second operand is a port number. If required to access port number over 255 -DX register should be used. IN AL,im.byteIN AL,DXIN AX,im.byteIN AX, DX

Example:IN AX, 4 ; get status of traffic lights.IN AL, 7 ; get status of stepper-motor.

OUT Output from AL or AX to port.First operand is a port number. If required to access port number over 255 -DX register should be used. OUT im.byte, ALOUT im.byte, AXOUT DX, ALOUT DX, AXExample:MOV AX, 0FFFh ; Turn on allOUT 4, AX ; traffic lights.

MOV AL, 100b ; Turn on the thirdOUT 7, AL

Instructions set

8086 has 117 instructions, these instructions divided into 6 groups:

1. Data transfer instructions

2. Arithmetic instructions26

Page 27: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

3. Logic instructions

4. Shift instructions

5. Rotate instructions

6. Advance instructions

1. Data Transfer Instructions

The microprocessor has a group of data transfer instructions that are provided to move data either between its internal registers or between an internal register and a storage location in memory. Some of these instructions are:

♣ MOV use to transfer a byte or a word of data from a source operand to a destination operand. These operands can be internal registers and storage locations in memory. Notice that the MOV instruction cannot transfer data directly between a source and a destination that both reside in external memory. For instance, flag bits within the microprocessors are not modified by execution of a MOV instruction.

EXAMPLES:

1. MOV DX, CS where DX=0100H

DX=CS=0100H

2. MOV SUM, AX DS=0200 H , SUM=1212H

PA=02000H+1212H=03212H

AL --------Memory location 03212H

AH ------Memory location 03213H

3. If DS contain 1234H what is the effect of executing the instruction

MOV CX,[0ABCDH]

CL loaded with the content of Memory location 12340H +ABCDH = 1CF0DH

And CH is loaded with the content of Memory location1234H + ABCDH +1 = 1CF0EH

♣ XCHG: in MOV instruction the original contents of the source location are preserved and the original contents of the destination are destroyed. But XCHG instruction can be used to swap data between two general purpose register or between a general purpose register and storage location in memory.

EXAMPLES:

1. XCHG AX, DX (AX) (DX)

2. XCHG SUM, BX

(DS (0) + SUM) BX27

Page 28: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

DS=02000 H + 1234 H =03234H

(3234) (BL)

(3235) (BH)

2. Arithmetic Instructions

Arithmetic instructions includes instructions for the addition,subtractions can be performed on numbers expressed in avariety of numeric data formats. The status that results from the execution of an arithmetic instruction is recoded in the flags of the microprocessor. The flags that are affected by arithmetic

instructions are CF, AF, SF, ZF, and PF.

♣ Addition: ADD, ADC, and INC

- ADD AX,BX

AX= AX+BX

EXAMPLE:

AX= 1100H, BX=0ABCH ADD AX, BX

1100H+ 0ABCH = 1BBCH = AX

- ADC AX, BX

AX=AX+BX+CF

- INC AH

AH= AH +1

EXAMPLE:

The original contents of AX, BL, memory location SUM, and CF are AX=1234H, BL= ABH, Sum=00CDH and CF=0 respectively, describe the result of execution the following sequence of instruction:

ADD AX, SUM

ADC BL, 05H

INC SUM

1. AX= 1234H + 00CDH = 4301H CF=0

2. BL= ABH +05H +0=B0H CF=0

3. SUM=00CDH + 1=00CEH CF=0

Subtraction: SUB, SBB, DEC, and NEG

28

Page 29: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

- SUB AX, BX

AX=AX – BX

- SBB AX, BX

AX= AX - BX – CF

EXAMPLE:

BX=1234H, CX=0123H, CF=0

SBB BX, CX

BX=1234H-0123H-0 =1111H

- DEC subtract 1 from its operand

- NEG BX (2's complement)

00H – BX

0000 + 2's complement of BX

EXAMPLE:

BX= 3A H NEG BX 0011 1010

0000 H +FFC6H 1100 0101 +

1

1100 0110

C 6

♣ Multiplication and Division MUL, DIV

- MUL CL

(AX)= AL* CL

- MUL CX

(DX, AX) = AX * CX

- DIV CL

(AH), (AL) = AX/CL

And AL the quotient

Where AH is the reminder

- DIV CX29

Page 30: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

DX, AX= (DX,AX)/CX

AX contain the Quotient

DX contain the reminder

EXAMPLE: MUL CL where AL=-1 CL= -2

AX= FF H * FE H = FD02 H

3. Logical Instructions (AND, OR, XOR, NOT)

Instructions AL

MOV AL, 0101 0101B 0101 0101 B

AND AL,0001 1111B 0001 0101 B

OR AL,1100 0000B 1101 0101 B

XOR AL,0000 1111B 1101 1010 B

NOT AL 0010 0101 B

4. Shift Instructions

The four types of shift instructions can perform two basic types of shift operations. They are the logical shift and arithmetic shift. Each of these operations can be performed to the right or to the left.

Instructions Meaning format Operation Flags affected

SAL/SHL Shift arithmetic left/shift logical left

SAL/SHL D, Count

Shift the D left by the number of bit positions equal to count and fill the vacated bits positions on the right with zeros

OF, CF

SHR Shift logical right

SHR D, Count Shift the D right by the number of bit position equal to count and fill the vacated bit positions on the left with zeros

OF, CF

30

Page 31: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

SAR Shift arithmetic right

SAR D, Count Shift the D right by the number of bit positions equal to count and fill the vacated bit positions on the left with the original most significant bit

OF,SF, ZF, AF, PF, CF

♣ SHL

CF

♣ SAL

CF

SHR

0

CF

SAR

CF

5- Rotate Instructions♣ ROL (Rotate Left)

CF

♣ RCR(Rotate

Carry Right)

♣ RCL 31

Page 32: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

(Rotate Carry left)

♣ ROR (RotateRight) CF

6. Advance instruction (Program and Control Instruction)

many of instructions that can be executed by the 8086 microprocessor are described, furthermore, these instructions use to write simple programs.

1. Flag control instructions

2. Compare instruction

3. Jump instructions

4. String instruction

1. Flag Control Instruction

The 8086 microprocessor has a set of flags which either monitor the status of executing instruction or control options available in its operation. The instruction set includes a group of instructions which when execute directly affect the settingof the flags. The instructions are:LAHF: load AH from flagsSAHF: store AH into flagsCLC: clear carry, CF=0STC: set carry, CF=1CMC: complement carry, CF= CFCLI: clear interrupt, IF=0STI: set interrupt, IF=1EXAMPLE:

Write an instruction to save the current content of the flags in memory location MEM1 and then reload the flags with the contents of memory location MEM2

32

Page 33: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Solution:

LAHF ;AH = flags register

;AH bit: 7 6 5 4 3 2 1 0 ; [SF] [ZF] [0] [AF] [0] [PF] [1] [CF]

;bits 1, 3, 5 are reserved.MOV MEM1, AHMOV AH, MEM2SAHF ;flags register = AH

;AH bit: 7 6 5 4 3 2 1 0 ; [SF] [ZF] [0] [AF] [0] [PF] [1] [CF]

;bits 1, 3, 5 are reserved.

2. Compare Instruction

There is an instruction included instruction set which can be used to compare two 8-bit number or 16-bit numbers. It is the compare (CMP) instruction. The operands can reside in a storage location in memory, a register within the MPU.

Instruction Meaning Format Operation Flag affected

CMP Compare CMP D,S D-S CF,AF,OF,PF,SF,

Destination SourceRegister Register Memory Register Memory Accumulator

Register Memory Register

Immediate Immediate Immediate

The process of comparison performed by the CMP instruction is basically a subtraction operation. The source operand is subtracted from the destination operand. However the result of this subtraction is not saved. Instead, based on the result the appropriate flags are set or reset.

EXAMPLE: lets find the result of comparing -5 with 127 , when we subtract -5-127 we get -132 (not in -128 .. 127), while in program we get wrong result (124), so OF =1 is set.

Mov al,0fbh ; Replacing the source operand with its 2's complement 0fbh=-5

33

Page 34: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Cmp al,07fh ; and subtract destination (127=7fh) from itRet 11111011

- 01111111 01111100 = 7ch =124

Flag condition is: CF=0,ZF=0,SF=0,OF=1,PF=1,AC=13. JUMP Instruction

The purpose of a jump instruction is to alter the execution path of instructions in the program. The code segment register and instruction pointer keep track of the next instruction to be executed. In this way, execution continues at an address other than that of the next sequential instruction. That is, a jump occurs to another part of the program. There two type of jump instructions:a. Unconditional jump. b. Conditional jump.In an unconditional jump, no status requirements are imposed for the jump to Occur. Instruction Meaning format operation Flags

affectedJMP Unconditional

jumpJMP operand Jump to address

specified by operand

None

Unconditional jump insruction

Locations skipped due to jump

Next instruction executed

34

Part I

JMP AA

Part II

AA XXX

Part III

Page 35: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Unconditional Jump program sequence

here's an example of JMP instruction:

mov ax, 5 ; set ax to 5. mov bx, 2 ; set bx to 2. jmp calc ; go to 'calc'.

back: jmp stop ; go to 'stop'.

calc:add ax, bx ; add bx to ax. jmp back ; go 'back'. stop:ret ; return to operating system.

conditional jump instruction, status conditions that exist at the moment the jump instruction is executed decide whether or not the jump will occur. If this condition or conditions are met, the jump takes place, otherwise execution continues with the next sequential instruction of the program. The conditions that can be referenced by a conditional jump instruction are status flags such as carry (CF), parity (PF),and overflow (OF).

Mnemonic Meaning Format Operation Flag effected

Jcc Conditional Jemp

Jcc operand If the specific condition cc is true, the jump to the address specified by the operand is initiated, otherwise the next instruction is executed

None

The following table lists some of the conditional jump instructions:MeaningMnemonic

If CF=1JC

If CF=0JNC

35

Page 36: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

If OF=1JO

If OF=0JNO

If SF=1JS

If SF=0JNS

If CX=0000JCXZ

If equal / the result=0JE / JZ

If not equal / not lessJGE / JNL

If above /if not below nor equal cf=0 and zf=0JA / JNBL

If above or equal / if not below cf=0JAE / JNB

If below / if not above , cf=1JB / JNAE

If below or equal / if not above CF=1 and zf=1JBE / JNA

If greater/ if not less nor equal zf=0 and sf=0JG /JNLE

If less or equal / if not graterJLE / JNG

If not equal / if not zero zf=0JNE / JNZ

If not parity (odd)/ if parity odd Pf=0JNP / JPO

If no parity (even) / if parity even ,PF=1JP / JPE

EXAMPLE: write a program to move a block of N bytes of data starting at offset address BLK1ADDR to another block starting at offset address BLK2ADDR. MOV SI, offset BLK1ADDRMOV DI, offset BLK2ADDRMOV CX, NNXTPT: MOV AH, [SI]MOV [DI], AHINC SIINC DI

36

Page 37: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

DEC CXJNZ NXTPTRETBLK1ADDR DB 1,2,3BLK2ADDR DB 5,6,7

Exp1 : to simulate if cond then stat1

If c > 20 then stat1

CMP C , 20

JLE REST

……

stat1

rest :

rest of program

EXP2 : For i=N1 To N2 Step N3 stat

MOV AL , N1

Rep:

stat

INC AL

OR

ADD AL ,N3

CMP AL , N2

JLE REP37

Page 38: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

rest of program

conditional jump came after these instructions, e.g:

1- ADD AL , BL 2 – SUB AL , BL 3- CMP AL , BL 4 – CMP BX , AX

JC LOC JZ ZERO JE label1 JA LOC1

Ex: write program to add ten numbers?

Lea si , list

mov ax , 0

mov cl , 1

adding: add ah,[si ]

inc si

inc cl

Cmp cl ,0Ah

JLE adding

mov sum , ah

ret

list db 1,2,3,4,5,6,7,8,9,1

sum db ?

4. Push and POP Instruction

It is necessary to save the contents of certain registers or some other main program parameters. These values are saved by pushing them onto the stack. Typically, these data correspond to registers and memory locations that are used by the subroutine. The instruction that is used to save parameters on the stack is the push (PUSH) instruction and that used to retrieve them back is the pop (POP) instruction. Notice a general-purpose register, a

38

Page 39: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

segment register (excluding CS), or a storage location in memory as their operand. PUSH and POP work with 16 bit values only.

♣ Execution of a PUSH instruction causes the data corresponding to the operand to be pushed onto the top of the stack. For instance, if the instruction is PUSH AX the result is as follows:

((SP)-1) (AH)

((SP)-2) (AL)

(SP) (SP)-2

This shows that the two bytes of the AX are saved in the stack part of memory and the stack pointer is decrement by 2 such that it points to the new top of the stack.

♣ On the other hand, if the instruction is POP AX Its execution results in

(AL) ((SP))

(AH) ((SP) + 1)

(SP) (SP)+2

The saved contents of AX are restored back into the register.

Example:

Mov ax,1234h

Push ax ;store value of Ax in stack

Mov ax,5678h ;modify the ax value

Pop ax ;restore the original value of ax

Ret

Example: use of stack to exchange values

Mov ax,1212h ;store 1212h in ax

Mov bx,3434h ;store 3434h in bx

Push ax ;store ax in stack

Push bx ;store bx in stack

Pop ax ;set ax to original value of bx

39

Page 40: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Pop bx ;set bx to original value of ax

ret

Exchange happens because stack uses LIFO (Last In First Out) algorithm.

♣ We also can save the contents of the flag register and if saved we will later have to restore them. These operations can be accomplished with the push flags (PUSHF) and pop flags (POPF) instructions, respectively. Notice the PUSHF save the contents of the flag register on the top of the stack. On the other hand, POPF returns the flags from the top of the stack to the flag register.

PUSHA :push all general purpose registers AX,CX,DX,BX,SP,BP,SI,DI in the stack.

Instruction Meaning Operation Flags affectedPUSHF PUSH FLAGS ONTO

STACK((sp))(flag) None

POPF POP FLAGS ONTO STACK

(flag)((SP)) OF,DF,IF,TF,SF,ZF,AF,PF,CF

5. String Instructions

The microprocessor is equipped with special instructions to handle string operations. By "string" we mean a series of data words or bytes that reside in consecutive memory locations. There are five basic string instructions in the instruction set of the 8086, these instruction are:

a. Move byte or work string ( MOVSB, and MOVSW).

b. Compare string (CMPS).

c. Scan string (SCAS).

d. Load string (LODS)

e. Store string (STOS).

They are called the basic string instructions because each defines and operations for one element of a string.

Move String

The instructions MOVSB, and MOVSW l 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. After the

40

Page 41: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

move is complete, the contents of both SI and DI are automatically incremented or decremented by 1 for a byte move and by 2 for a word move. Remember the fact that the address pointers in SI and DI increment or decrement depends on how the direction flag DF is set.

MOVSB; Copy byte at DS:[SI] to ES:[DI]. Update SI and DI.Algorithm:

ES:[DI] = DS:[SI] if DF = 0 then

o SI = SI + 1o DI = DI + 1

else if DF=1 then

o SI = SI - 1o DI = DI - 1

flag is unchanged

Example

CLD ; clear direction flag

LEA SI, a1

LEA DI, a2

MOV CX, 5

REP MOVSB

RET

a1 DB 1,2,3,4,5

a2 DB 5 DUP(0)

note: Repeat following MOVSB, MOVSW, LODSB, LODSW, STOSB, STOSW instructions CX times. Algorithm:check_cx:

if CX <> 0 then

do following chain instruction CX = CX - 1 go back to check_cx

else

exit from REP cycle

41

Page 42: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

MOVSW: Copy word at DS:[SI] to ES:[DI]. Update SI and DI.

Algorithm:

ES:[DI] = DS:[SI] if DF = 0 then

o SI = SI + 2o DI = DI + 2

else

o SI = SI - 2o DI = DI - 2

Compare Strings and Scan Strings

The CMPS instruction can be used to compare two elements in the same or different strings. It 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; therefore, the operation does not affect the operands in any way CMPS BYTE

The source element is pointed to by the address in SI with respect to the current value in DS and the destination element is specified by the contents of DI relative to the contents of ES. Both SI and DI are updated such that they point to the next elements in their respective string.

The scan string (SCAS) instruction is similar to CMPS, however, it compares the byte or word element of the destination string at the physical address derived from DI and ES to the contents of AL or AX, respectively. The flags are adjusted based on this result and DI incremented or decremented.

CMPSB: Compare bytes: ES:[DI] from DS:[SI].

Algorithm:

DS:[SI] - ES:[DI] set flags according to result:

OF, SF, ZF, AF, PF, CF if DF = 0 then

o SI = SI + 1o DI = DI + 1

else

o SI = SI - 1o DI = DI - 1

CMPW:Compare words: ES:[DI] from DS:[SI]. Algorithm: DS:[SI] - ES:[DI]

42

Page 43: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

set flags according to result:OF, SF, ZF, AF, PF, CF

if DF = 0 then o SI = SI + 2o DI = DI + 2

else

o SI = SI - 2o DI = DI - 2

SCASB :Compare bytes: AL from ES:[DI].

Algorithm:

AL - ES:[DI] set flags according to result:

OF, SF, ZF, AF, PF, CF if DF = 0 then

o DI = DI + 1

else

o DI = DI - 1

SCASW:Compare words: AX from ES:[DI].

Algorithm:

AX - ES:[DI] set flags according to result: OF, SF, ZF, AF, PF, CF if DF = 0 then

o DI = DI + 2

else

o DI = DI – 2

STOSB:Store byte in AL into ES:[DI]. Update DI.

Algorithm:

ES:[DI] = AL if DF = 0 then

o DI = DI + 1

43

Page 44: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

else

o DI = DI - 1

STOSW:Store word in AX into ES:[DI]. Update DI.

Algorithm:

ES:[DI] = AX if DF = 0 then

o DI = DI + 2

else

o DI = DI – 2

LODSB:Load byte at DS:[SI] into AL. Update SI.

Algorithm:

AL = DS:[SI] if DF = 0 then

o SI = SI + 1

else SI = SI - 1

LODSW:Load word at DS:[SI] into AX. Update SI.

Algorithm:

AX = DS:[SI] if DF = 0 then

o SI = SI + 2

else SI = SI - 2

Example:

LEA SI, a1MOV CX, 5REP LODSW ; finally there will be 555h in AX.RETa1 dw 111h, 222h, 333h, 444h, 555h6-Iteration Instructions

This instruction uses CX register to save the number of iterations to execute a number of assembly instructions , each time these instructions are executed are called cycle. and in each cycle CX is decremented , then a decision is made by microprocessor to return back for another cycle or not depend on CX value , if its zero then exit from repetition cycle.

44

Page 45: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

1-Loop instruction

Ex: mov cx,10

Xx: ------ True------ if CX<>0------Loop xx

false

LOOP:Decrease CX, jump to label if CX not zero.

Algorithm:

CX = CX - 1 if CX <> 0 then

o jump

else no jump, continue

Example:

MOV CX, 5

lea si,varlabel1: mov [si],cx inc si LOOP label1 RETVar db ?

LOOPE: Decrease CX, jump to label if CX not zero and Equal (ZF = 1).

Algorithm:

CX = CX - 1 if (CX <> 0) and (ZF = 1) then

o jump

else

o no jump, continue

Example:; Loop until result fits into AL alone, or 5 times. The result will be over 255, on third loop (100+100+100)=12C h, so loop will exit.

MOV AX, 0 MOV CX, 5label1:

45

Page 46: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

ADD AX, 100 ;100=64h CMP AH, 0 LOOPE label1 RET

LOOPNZ: Decrease CX, jump to label if CX not zero and ZF = 0.

Algorithm:

CX = CX - 1 if (CX <> 0) and (ZF = 0) then

o jump

else no jump, continue

Example:; Loop until '7' is found, or 5 times.

MOV SI, 0 MOV CX, 5label1: MOV AL, v1[SI] INC SI ; next byte (SI=SI+1). CMP AL, 7 LOOPNZ label1 RET v1 db 9, 8, 7, 6, 5

Subroutine (procedure): A subroutine is a group of instructions that usually performs one task. A subroutine is a reusable section of the software that is stored in memory once, but used as often as necessary.

CALL and RET instructions: the CALL instruction links to the procedure, and RET instruction returns from procedure. Like JMP instruction, CALL has two types of operations:

1. Intrasegment call: In this case execution of instruction CALL case:

• The content of IP (the offset address of the instruction that immediately follows the CALL) is saved on the stack.

• The stack pointer (SP) is decremented by two. 46

Page 47: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

• The operand of CALL instruction (the offset of the first instruction of the subroutine) is loaded into IP.

2. Intresegment call: In this case execution of instruction CALL case:

• The content of CS and IP (the address of the instruction that immediately follows the CALL) is saved on the stack. • The stack pointer (SP) is decremented by four.

• The operand of CALL instruction (the segment & offset of the first instruction of the subroutine) is loaded into IP and CS.

MnemMeaning Format Operation Flags

CALLSubroutine call

CALL operand

Execution contents from the address of the subroutine specified by the operand. Information required to return back to the main program such as IP and CS are saved on the stack

None

Every subroutine must be ended by executing a RET instruction. Note that its execution cause the value of IP or both the value of IP and CS that were saved on the stack to be returned back to their corresponding registers and the stack pointer to be adjusted appropriately. In this way, program control is returned to the instruction that immediately follows the CALL instruction in program memory.

Example 7-3: Write a subroutine to display a character stored in DL register. Use this subroutine to print ‘TEST’ word.

Solution: The INT 21 interrupt instruction is used to print a character stored in DL register. The subroutine and the program are as shown below:

MOV DL, 'T' CALL M1 MOV DL,'E' CALL M1 MOV DL,'S'CALL M1 Main program

47

Page 48: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

MOV DL,'T' CALL M1 HLT

M1 PROC

MOV AH, 2

INT 21H subroutine

RET

M1 ENDP

MnemMeaning Format Operation Flags

RETReturn RET or RET operand Return to the main program by

restoring IP (and CS for far-proc). If operand is present, it is added to the contents of SP.

None

CALL procedure name Transfers control to procedure, return address is (IP) is pushed to stack. label 4-byte address may be entered in this form: 1234h:5678h, first value is a4-byte address segment second value is an offset (this is a far call, so CS is also pushed to stack).

Example:

ORG 100h ; for COM file.

CALL p1

ADD AX, 1

RET ; return to OS.

Procedures

Procedure is a part of code that can be called from your program in order to make some specific task. Procedures make program more structural and easier to understand. Generally procedure returns to the same point from where it was called.

The syntax for procedure declaration:

48

Page 49: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

name PROC

      ; here goes the code      ; of the procedure ...

RETname ENDP

name - is the procedure name, the same name should be in the top and the bottom, this is used to check correct closing of procedures.

Probably, you already know that RET instruction is used to return to operating system. The same instruction is used to return from procedure (actually operating system sees your program as a special procedure). The ret (return) instruction returns control to the caller of a subroutine. It does so by popping the return address off the stack and transferring control to the instruction at this return address. Intrasegment (near) returns pop a 16 bit return address off the stack into the IP register. An intersegment (far) return pops a 16 bit offset into the IP register and then a16 bit segment value into the CS register. Clearly, you must match a near subroutine call with a near return and a far subroutine call with a corresponding far return. If you mix near calls with far returns or vice versa, you will leave the stack in an inconsistent state and you probably will not return to the proper instruction after the call. Of course, another important issue when using the call and ret instructions is that you must make sure your subroutine doesn’t push somethingonto the stack and then fail to pop it off before trying to return to the caller. Stack problems area major cause of errors in assembly language subroutines. Consider the following code:Subroutine: push axpush bx...pop bxret...call SubroutineThe call instruction pushes the return address onto the stack and then transfers control to the first instruction of subroutine. The first two push instructions push the ax and bx registersonto the stack, most probably in order to preserve their value because subroutine modifies them. Unfortunately, a programming error exists in the code above, subroutine only pops bx from the stack, it fails to pop ax as well. This means that when subroutine tries to return to the caller, the value of ax rather than the return address is sitting on the top of the stack.subroutine returns control to the address specified by the initial PROC and ENDP are compiler directives, so they are not assembled into any real machine code. Compiler just remembers the address of procedure.

49

Page 50: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

to call a procedure, here is an example: CALL m1MOV AX, 2

RET ; return to operating system.

m1 PROCMOV BX, 5RET ; return to caller.m1 ENDP

END

the above example calls procedure m1, does MOV BX, 5, and returns to the next instruction after CALL: which is MOV AX, 2.

There are several ways to pass parameters to procedure, the easiest way to pass parameters is by using registers, here is another example of a procedure that receives two parameters in AL and BL registers, multiplies these parameters and returns the result in AX register:

MOV AL, 1MOV BL, 2

CALL m2CALL m2CALL m2CALL m2

RET ; return to operating system.

m2 PROCMUL BL ; AX = AL * BL.RET ; return to caller.m2 ENDPENDIn the above example value of AL register is update every time the procedure is called, BL register stays unchanged, so this algorithm calculates 2 in power of 4,so final result in AX register is 16 (or 10h). Here goes another example, that uses a procedure to print a Hello World! message:

LEA SI, msg ; load address of msg to SI.

CALL print_me

50

Page 51: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

RET ; return to operating system.; this procedure prints a string, the string should be null terminated (have zero in the end),; the string address should be in SI register:print_me PROCnext_char: CMP b.[SI], 0 ; check for zero to stop JE stop ;

MOV AL, [SI] ; next get ASCII char.

MOV AH, 0Eh ; teletype function number. INT 10h ; using interrupt to print a char in AL.

ADD SI, 1 ; advance index of string array.

JMP next_char ; go back, and type another char.

stop:RET ; return to caller.print_me ENDPmsg DB 'Hello World!', 0 ; null terminated string.END

"b." - prefix before [SI] means that we need to compare bytes, not words. When you need to compare words add "w." prefix instead. When one of the compared operands is a register it's not required because compiler knows the size of each register.

Interrupts:The int (for software interrupt) instruction is a very special form of a call instruction. while the call instruction calls subroutines within your program, the INT instruction calls system routines and other special subroutines. The major difference between interrupt service routines and standard procedures is that you can have any number of different procedures in an assembly language program, while the system supports a maximum of 256 different interrupt service routines. A program calls a subroutine by specifying the address of that subroutine; it calls an interrupt service routine by specifying the interrupt number for that particular interrupt service routine.

INT instruction form is INT nn (where “nn” is a value between 0 and 255). It allows you to call one of 256 different interrupt routines.

generally we will use hexadecimal numbers (0 to FFh).You may think that there are only 256 functions, but that is not correct. Each interrupt may have sub-functions. To specify a sub-

51

Page 52: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

function AH register should be set before calling interrupt. Each interrupt may have up to 256 sub-functions (so we get 256 * 256 = 65536 functions). In general AH register is used, but sometimes other registers may be in use. Generally other registers are used to pass parameters and data to sub-function.

Although you can use the INT instruction to call procedures (interrupt service routines) you’ve written, the primary purpose of this instruction is to make a system call. A system call is a subroutine call to a procedure provided by the system, such as a DOS , PC-BIOS, mouse, or some other piece of software resident in the machine before your program began execution. Since you always refer to a specific system call by its interrupt number, rather than its address, your program does not need to know the actual address of the subroutine in memory. The INT instruction provides dynamic linking to your program. The CPU determines the actual address of an interrupt service routine at run time by looking up the address in an interrupt vector table.

The only problem with the INT instruction is that it supports only 256 different interrupt service routines. MS-DOS alone supports well over 100 different calls. BIOS and other system utilities provide thousands more. The common solution most of the system calls use is to employ a single interrupt number for a given class of calls and then pass a function number in one of the 80x86 registers (typically the ah register). For example, MS-DOS uses only a single interrupt number, 21h. To choose a particular DOS function, you load a DOS function code into the ah register before executing the INT 21h instruction.

For example, to terminate a program and return control to MS-DOS, you would normally load AH with 4Ch and call DOS with the INT 21h instruction:

mov ah, 4ch ;DOS terminate opcode.

INT 21h ;DOS call

The BIOS keyboard interrupt is another good example. Interrupt 16h is responsible for testing the keyboard and reading data from the keyboard. This BIOS routine provides several calls to read a character from the keyboard. To choose a particular operation, you load the function number into the AH register before executing INT 16h.

The following example uses INT 10h sub-function 0Eh to type a "Hello!" message. This functions displays a character on the screen, advancing the cursor and scrolling the screen as necessary.

ORG 100h ; instruct compiler to make simple single segment .com file.; The sub-function that we are using does not modify the AH register on return, so we may set it only once.

MOV AH, 0Eh ; select sub-function.

52

Page 53: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

; INT 10h / 0Eh sub-function, receives an ASCII code of the character that will be printed; in AL register.

MOV AL, 'H' ; ASCII code: 72INT 10h ; print it!

MOV AL, 'e' ; ASCII code: 101INT 10h ; print it!

MOV AL, 'l' ; ASCII code: 108INT 10h ; print it!

MOV AL, 'l' ; ASCII code: 108INT 10h ; print it!

MOV AL, 'o' ; ASCII code: 111INT 10h ; print it!

MOV AL, '!' ; ASCII code: 33INT 10h ; print it!

RET ; returns to operating system.

Example 2: Write a subroutine to display a character stored in DL register. Use this subroutine to print ‘TEST’ word.

Solution: The INT 21 interrupt instruction is used to print a character stored in DL register. The subroutine and the program are as shown below:

MOV DL, 'T' CALL M1 MOV DL,'E' CALL M1 MOV DL,'S'CALL M1 Main program MOV DL,'T' CALL M1 HLT

M1 PROC MOV AH, 2 INT 21H subroutine

53

Page 54: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

RET M1 ENDP

Ex:; this procedure prints a string, the string should be null terminated (have zero in the end),; the string address should be in SI register:print_me PROCnext_char: CMP b.[SI], 0 ; check for zero to stop JE stop ; MOV AL, [SI] ; next get ASCII char.

MOV AH, 0Eh ; teletype function number. INT 10h ; using interrupt to print a char in AL.

ADD SI, 1 ; advance index of string array.

JMP next_char ; go back, and type another char.

stop: RET ; return to caller.print_me ENDPmsg DB 'Hello World!', 0 ; null terminated string.END

"b." - prefix before [SI] means that we need to compare bytes, not words. When you need to compare words add "w." prefix instead. When one of the compared operands is a register it's not required because compiler knows the size of each register.Interrupt Instructions: Interrupt Instructions branch the execution to or from a special procedure called interrupt service procedure.Format FunctionINT # Execute interrupt service routine for type #INTO Interrupt on overflow branches to a procedure if OF is setIRET Return from interrupt service procedure

When executing The interrupt instruction, branch is done to interrupt service routine specified by its number . Prior to branching it saves flags and return address in stack, and gets both segment and offset of ISR from interrupt vector table.The interrupt on overflow instruction branches to a procedure if OF is set. Before branching, it saves flags and return address in stack. It gets of procedure from interrupt vector table.The IRET instruction is the last instruction in interrupt service routine, which causes the execution to resume the interrupt ed program. It gets back the flags and return address from

54

Page 55: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

stack. The simple RET instruction is not used to return back from interrupt service routine since it dose not restore the flags back from stack.

Example: INTOAlgorithm: if OF = 1 then INT 4; -5 - 127 = -132 (not in -128..127); the result of SUB is wrong (124),; so OF = 1 is set:

EX: ON INTO Interrupt 4 if Overflow flag is 1.MOV AL, -5SUB AL, 127 ; AL = 7Ch (124)INTO ; process error.RET

Assembler DirectivesPrograms using assemblers include assembler dependent instruction (in addition to assembly language instruction ) called assembler directives .A simple assembly language program for computing the product of two unsigned binary numbers and storing the product in memory is given in listing 2.1.it demonstrates the use of a few assembler directives .

Listing 2.1: assembly language program to compute the product of two unsigned binary numbers.

Mydata segment Value 1 DB 1AH ,first value Value 2 DB 2BH ,second value Product DW 1 DUP (0) ,result of product Mydata ENDS

MYCODE SEGMENT ASSUME CS:MYCODE , DS: MYDATASTART: MOV AX, MYDATA ,to initialize DS MOV DS, AX MOV AL, VALUE 1 ,first value in AL MUL VALUE 2 ,MULTIPLY by second VALUE MOV PRODUCT , AX ,STORE PRODUCT MYCODE ENDS END START

Assembler DirectivesPrograms using assemblers include assembler dependent instruction (in addition to assembly language instruction ) called assembler directives .A simple assembly language program for

55

Page 56: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

computing the product of two unsigned binary numbers and storing the product in memory is given in listing 2.1.it demonstrates the use of a few assembler directives .

Listing 2.1: assembly language program to compute the product of two unsigned binary numbers.

Mydata segment Value 1 DB 1AH ,first value Value 2 DB 2BH ,second value Product DW 1 DUP (0) ,result of product Mydata ENDS

MYCODE SEGMENT ASSUME CS:MYCODE , DS: MYDATASTART: MOV AX, MYDATA ,to initialize DS MOV DS, AX MOV AL, VALUE 1 ,first value in AL MUL VALUE 2 ,MULTIPLY by second VALUE MOV PRODUCT , AX ,STORE PRODUCT MYCODE ENDS END START

SEGMENT and ENDSThe assembler directives SEGMENT and ENDS are used to group data items or instructions in the program.Group of statement contained between the two directives is called a logical segment.for each logical segment .a name is assigned in the program . Statements MYDATA SEGMENT and MYDATA ENDS in listing 2.1 set up a logical segment with name MYDATA . statements MYCODE SEGMENT and MYCODE ENDS set up another logical segment with name MYCODE. Segment MYDATA contains data and segment MYCODE contains instruction for the program.

DB, DW and DDThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data. Statement VALUE1 DB 1AH and VALUE2 DB 2BH in listing 2.1 declare two variables of type bytes and assign names VALUE1 asnd VALUE2. The statements further direct the assembler to allocate a byte space in memory for each variable and fill with initial value1AH and 2BH respectively.Statment PRODUCT DW 1 DUP (0) declares a variable of type word and gives name PRODUCT to it. It directs the assembler to allocate 2 bytes space to PRODUCT to accommodate one word and fill (DUP) with initial value of 0000h.

56

Page 57: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

this program for find the sum of ten number ------

stackseg segment para 'stack'

dw 32 dup (?)

stackseg ends

dataseg segment para 'data'

list db 1,2,3,4,5,6,7,8,9,1

sum db ?

dataseg ends

codeseg segment para 'code'

main proc far

assume cs:codeseg , ds:dataseg , ss:stackseg , Es:dataseg

push Ds

sub Ax ,Ax

push Ax

mov Ax, dataseg

mov Ds , Ax

mov Es , Ax

Lea si , list

mov ax , 0

mov cl , 1

adding: add ah,[si ]

inc si

inc cl

57

Page 58: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Cmp cl ,0Ah

JLE adding

mov sum , ah

ret

main endp

codeseg ends

end main

Exp2: Write assembly language program to find the factorial of number , and then store the result in the variable fact , where fact(n)= n (n-1) (n-2)…..(3)(2) (1)

Solution:

; this program to find the factorial of a number

;------------------------------------------------------------

Stackseg Segment para stack 'stack'

DB 64 dup(?)

Stackseg Ends

Dataseg Segment para 'data'

Num dw 4

fact dw 0

Dataseg Ends

Codeseg Segment para 'code'

FACTORIAL Proc Far

Assume ss:stackseg , ds:dataseg , Cs:codeseg

Push Ds

Mov Ax, 0

58

Page 59: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Push AX

Mov Ax, Dataseg

Mov DS , AX

MOV DX ,0 ; INITALIZE THE DE REGESTER

MOV AL ,1 ; INITALIZE THE FACTORAIL TO 1

MOV BX,NUM ; BX= NUMBER TO DIND ITS FACTORAIAL

MOV CX , BX ; COUNTER = BX

DEC CX ; COUNTER = COUNTER -1

LOOP1: MUL BX ; N (N -1)

DEC BX ; N = N -1

LOOP LOOP1 ; LOOP N-1 TIMES

MOV FACT , AX ; FACT = AX:DX

MOV FACT+1 , DX

RET

FACTORIAL Endp

codeseg Ends

End FACTORIAL

Exp3: write assembly language program that identify set of numbers in table , and then find the average of this number and put it in the average and the remainder in the variable remainder

Solution:

59

Page 60: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

; this program to find the average of numbers sored in table

;-----------------------------------------------------------

Stackseg Segment para stack 'stack'

DB 64 dup(' ')

Stackseg Ends

Dataseg Segment para 'data'

table db 5,6,7,2,4,8,9

average db 0

remainder db 0

Dataseg Ends

Codeseg Segment para 'code'

Average_p Proc Far

Assume ss:stackseg , ds:dataseg , Cs:codeseg

Push Ds

Mov Ax, 0

Push AX

Mov Ax, Dataseg

Mov DS , AX

Mov BX , 0

Mov AL , 0 ; sum = 0

sum: ADD AL , Table[Bx] ; add element to sum

Inc bx ; mov pointer to the next element

60

Page 61: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Cmp Bx , 8 ; check if last

JE End_sum ; if true goto end_sum paragragh

JMP sum ; else continue with summing element

End_sum: Mov ah ,0 ; higer byte=0

Mov DL , 7 ; number of elements in array

div DL ; average = (ah:al)/ dl

mov average , ah ;store average

mov remainder , al ;store fraction

Ret

Average_p Endp

codeseg Ends

End Average_p

Exp4: Write assembly language program that find the maximum number in list of given bytes .

Solution:

; This program to find the maximum number in list of bytes

;-----------------------------------------------------------

Stackseg Segment para stack 'stack'

DB 64 dup(' ')

Stackseg Ends

Dataseg Segment para 'data'

table db 2,1,4,9,3,2,6,8,'\'

max db 0

61

Page 62: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Dataseg Ends

Codeseg Segment para 'code'

max_num Proc Far

Assume ss:stackseg , ds:dataseg , Cs:codeseg

Push Ds

Mov Ax, 0

Push AX

Mov Ax, Dataseg

Mov DS , AX

Mov Bx, 0

Mov AL , table[Bx] ;first number is the maximum

INC BX

Compaire :CMP table[bx] , AL ; chech if max <= to the next element

JLE next_number ; if true goto next_number

Mov AL , table[bx] ; else max=the other element

Next_number:INC BX ; Bx= bx + 1

CMP table[BX] , '\' ; check if end

JE end1 ; if true end

Jmp compaire ; else compaire

62

Page 63: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

End1 : Mov max , AL ; as final AL to Max

Ret

Max_num Endp

codeseg Ends

End Max_num

How can more than one device interrupt?Computer typically have more than one I/O device requesting interrupt service, like keyboard, hard disk, floppy disk, printer all generate an INT when they required the attention to CPU. When more than one device INT CPU, we need a mechanism topriority these INT (if they come at the same time) and forward only one INT request at a time to the CPU while keeping other INT request pending for their service.D M

Input and OutputInput & Output (I/O) devices provide the means by which a computer system can interact with the outside worlds. An I/O device can be a purely input device (e.g. KB, Mouse), a purely output device (printer, screen), or both input and output device like (e.g. disk) Regardless of the intended purpose of I/O devices, all communication with these devices must involve the system bus. However, I/O devices are not directly connected to the system bus. Instead, there is usually, On I/O controller that acts as an interface between the system and the I/O devices.Accessing I/O devicesAs programmer, you can have direct control to any of the I/O devices (through their associated I/O controller). It is a waste of time and effort if every one had to develop their own routines to access I/O devices. In addition system resource could be abused either intentionally or accidentally. For instance, and improper disk drive could erase the content of a disk due to a bug in the driver routine. To avoid this problem and to provide a standard way of accessing I/O devices, OS provide routine to convent all access I/O devices. Typically, access to I/O devices can be obtain from two layer of

63

Page 64: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

system software, the basic I/O system (BIOS) and the OS,BIOS is ROM resident and is a collection of routine that control the I/O devices. Both provide access to routine that control I/O devices through a mechanism called INT (interrupt).I/O Address Space and Data TransferAs we know I/O ports in the 8086 MPU can be either byte wide or word wide. The port that is accessed for input or output of data is selected by an I/O address. The address is specified as port of the instruction that performs the I/O operation.I/O addresses are 16 bit in length and are output by the 8086 to the I/O interface over bus lines AD0 through AD15, the most significant bit A16-A19 of the memory address are held at the 0 logic (not used).Below Figure 1 show a map of I/O address space of the 8086 system. This is an independent 64-KB address space that is dedicated for I/O devices. Notice that its address range is from 000016-FFFF16. Moreover, notice that the eight ports located from address 00F8 to 00FF are specified as reserved. These port addresses are reserved by Intel for use in their future HW and SW products. Data transfer between the MPU and I/O devices are performed over the data bus. Word transfer take place over the complete data bus D0 to D15, and can required either one or two bus cycle.Ports: a port is a device that connects the processor to the external world through a port processor, receive a signal from an input device and send a signal to an output device.Input / Output InstructionThe instruction set contains one type of instruction that transfer information to an I/O device (OUT) and another to read information from an I/O device (IN).Example 1: write a sequence of inst that will output FF16 to a byte wide output port at address AB16 of the I/O addresses space. Solution: first the AL register is loaded with FF16 as an immediate operand in the instructionMOV AL, 0FFHNow the data in AL can be output to the byte wide output port with the instructionOUT 0ABH, AL

64

Instruction Meaning Format Operation

IN Input direct IN ACC, PORT ACC PORTInput indirect IN ACC, DX ACC (DX)

OUT Output direct OUT PORT,ACC PORT ACCOutput indirect OUT DX, ACC (DX) ACC

Page 65: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

Example2: write a series of instruction that will output FF16 to an output port located at address B00016 of the I/O address space Solution: the DX register must first be loaded with the address of the output portMOV DX, 0B000HNext, the data that is to be output must be loaded into ALMOV AL, 0FFHFinally, the data are output with the instructionOUT DX, AL

Example 3: data are to be read in from two byte wide input port at address AA16 and A916 respectively, and then output to a word wide output port at address B00016. Write a sequence of instruction to perform this I/O operation:Solution: we first read in a byte from the port at address AA16 into AL and move it to AHIN AL, 0AA16MOV AH, ALThe other byte can be read into ALIN AL, 0A9HTo writhe out the word of data in AX, we can load DX with the addressB00016 and use a variable output instructionMOV DX, 0B000HOUT DX, AX

Multiple interrupts.The multiple interrupts can occur; two approaches can be taken to dealing with multiple interrupts. The first is to disable interrupt while an interrupt is being processed. A disabled interrupt simply means that the CPU will ignore that interrupt request signal. If an interrupt occurs during this time, it generally remains Pending (awaiting) and will be checked by the CPU, after the CPU has enabled interrupts. Thus, when a user program is executing and an interrupt occurs, interrupts are enabled before resuming the user program and the processor checks to see if additional interrupts have occurred. This approach is nice and simple, as interrupts are handled in strict sequential order (figure a).The drawback to the preceding approach is that it does not take into account relative priority or time critical needs. For example, when input arrives from the communications line, it may need to be absorbed rapidly to make room for more

65

Page 66: academics.su.edu.krd · Web viewThe define byte ,DB, define word ,DW, and define double word ,DD, directives are used to assign names to variable of 8-bit, 16-bit aqnd 32-bit data

input. If the first batch of input has not been processed before the second batch arrives, data may be lost.A second approach is to define priorities for interrupts and to allow an interrupt of higher priority to cause a lower priority interrupt handler to be it interrupted (fig- b).

(a) Sequential interrupt processing.

(b) Nested interrupt processing

66