MicroprocessorUnit 312 min read
Addressing Modes & ALP in 8086: Syntax, Flags, and Program Design
Unit 3 of Microprocessor covers the 8086’s addressing modes (how operands are specified), assembly language programming (syntax, directives, and program flow), and flag manipulation—essential for writing efficient low-level code. Learn how to calculate memory addresses, trace program execution, and design real-world ap
TAKEAWAYS:
- Addressing modes determine how operands are accessed (register, memory, immediate, etc.), directly impacting instruction efficiency and memory usage.
- Flags (ZF, CF, SF, etc.) store arithmetic/logic results and enable conditional branching—critical for loops and decisions in ALP.
- Assembly syntax uses directives like
MOV,JMP, andCALL; mastering them lets you write programs that interact with hardware (e.g., I/O ports). - String operations (
MOVSB,CMPSB) and loop constructs (LOOP,REP) are used in real-time systems like eSewa’s transaction validation or Khalti’s payment routing. - Debugging ALP requires tracing registers, memory, and flags—skills needed for embedded systems (e.g., NTC’s smart meters or Ncell’s SIM authentication).
- Exam focus: Expect programming questions (e.g., reverse a string), flag analysis, and addressing mode calculations—always show step-by-step traces.
1. Addressing Modes in 8086: How the CPU Finds Operands
The 8086 uses 8 addressing modes to specify operands. Each mode determines how the CPU calculates the effective address (EA) or directly uses the operand. Visualizing these modes helps avoid mistakes in ALP.
1.1 The 8 Addressing Modes (with Mermaid Table)
| Mode | Syntax Example | EA Calculation | Notes |
|---|---|---|---|
| Immediate | MOV AL, 5 |
Operand is the instruction itself. | No memory access; data is literal. |
| Register | ADD BL, CL |
Operand is in a register (e.g., AL, BX). |
Fastest mode; no memory access. |
| Direct | MOV [1234], AX |
EA = 16-bit address (e.g., 1234). |
Limited to 64KB; slow for large data. |
| Register Indirect | MOV AX, [BX] |
EA = value in BX (or SI, DI, BP). |
Enables dynamic memory access. |
| Based Indexed | MOV AX, [BX+SI] |
EA = BX + SI (or BX + DI). |
Used for array traversal. |
| Based Indexed w/ Displacement | MOV AX, [BX+SI+10] |
EA = BX + SI + 8/16-bit displacement. |
Flexible for structured data. |
| String | MOVSB |
Uses SI/DI; auto-increments. |
Optimized for block memory operations. |
| Relative | JMP SHORT Label |
EA = IP + 8-bit displacement. | Used for jumps within ±128 bytes. |
Why this matters:
- Direct vs. Indirect: Direct addressing (
MOV [1234], AX) is slow because the CPU must fetch the operand from memory. Indirect modes (e.g.,[BX]) are faster for loops or arrays. - Example: In Pathao’s ride-matching algorithm, the CPU uses based indexed addressing (
[BX+SI]) to scan a list of nearby drivers stored in memory.
(Note: The actual die highlights the internal data paths for address calculation.)
2. Assembly Language Programming (ALP): Syntax and Directives
ALP for 8086 uses mnemonics (e.g., MOV, ADD) and directives (e.g., DATA, CODE) to assemble into machine code. Mastering syntax is key to passing exam questions.
2.1 Key Directives and Segments
The 8086 requires segment registers (CS, DS, SS, ES) to manage memory. A typical program structure:
STACK SEGMENT STACK 'STACK'
DB 100 DUP(?) ; Reserve 100 bytes for stack
STACK ENDS
DATA SEGMENT
MSG DB 'Hello$' ; String with '$' for DOS display
NUM1 DB 5
NUM2 DB 10
DATA ENDS
CODE SEGMENT
ASSUME CS:CODE, DS:DATA, SS:STACK
START:
MOV AX, DATA
MOV DS, AX ; Initialize DS to DATA segment
; ... instructions ...
CODE ENDS
END START
Real-world tie-in:
- Khalti’s payment gateway uses similar segment-based memory management to isolate transaction data (
DATAsegment) from executable code (CODEsegment).
2.2 Common Instructions by Category
mindmap
root((8086 Instructions))
Data Transfer
MOV: Copy data between registers/memory.
XCHG: Swap registers.
PUSH/POP: Stack operations.
Arithmetic
ADD/SUB: Basic math.
INC/DEC: Increment/decrement.
MUL/DIV: Multiplication/division.
Logical
AND/OR/XOR: Bitwise ops.
NOT: Bitwise negation.
TEST: Check bits without modifying.
Control Flow
JMP: Unconditional jump.
JZ/JNZ: Conditional jumps (flag-based).
CALL/RET: Subroutines.
String
MOVSB: Move byte from [SI] to [DI].
CMPSB: Compare strings.
SCAS: Scan string.
I/O
IN/OUT: Port operations.Worked Example: Reverse a String (Exam-Style)
Problem: Write an ALP to reverse the string "abc" stored in memory and display it.
Solution:
DATA SEGMENT
STR DB 'abc$'
LEN EQU $-STR-1 ; Length = 3
DATA ENDS
CODE SEGMENT
MOV AX, DATA
MOV DS, AX
LEA SI, STR ; SI = start of string
LEA DI, STR+LEN-1 ; DI = end of string
MOV CX, LEN/2 ; Loop counter (swap half the string)
REVERSE_LOOP:
MOV AL, [SI] ; Load char from start
XCHG AL, [DI] ; Swap with char at end
MOV [SI], AL
INC SI ; Move pointers inward
DEC DI
LOOP REVERSE_LOOP
; Display reversed string (DOS interrupt)
MOV AH, 09h
LEA DX, STR
INT 21h
CODE ENDS
END
Trace for LEN=3:
| Step | SI | DI | [SI] | [DI] | Action |
|---|---|---|---|---|---|
| Initial | 0 | 2 | 'a' | 'c' | |
| Iter 1 | 0 | 2 | 'c' | 'a' | Swap [0] and [2] |
| Iter 2 | 1 | 1 | 'b' | 'b' | Loop ends (CX=0) |
Result: String becomes "cba". |
Real-world link:
- eSewa’s user input validation reverses strings to check for palindromes (e.g., "madam") before processing transactions.
3. Flags in 8086: The CPU’s Decision-Making Tools
Flags are 1-bit status registers set by arithmetic/logic instructions. They enable conditional jumps and loops.
3.1 The 6 Key Flags
| Flag | Name | Set When... | Example Instruction | Use Case |
|---|---|---|---|---|
| ZF | Zero Flag | Result = 0 | CMP AX, BX |
JZ Label if AX == BX |
| CF | Carry Flag | Unsigned overflow (e.g., 9+7) | ADD AL, BL |
JC Label for unsigned > max |
| SF | Sign Flag | Result is negative (MSB=1) | SUB AX, BX |
JS Label for negative results |
| OF | Overflow Flag | Signed overflow (e.g., 127+1) | ADD AX, BX |
JO Label for signed overflow |
| PF | Parity Flag | LSB count is even | AND AL, BL |
Rarely used; checksums |
| AF | Auxiliary Flag | BCD overflow (e.g., 0x09 + 0x01) | ADD AL, 01h |
JNA Label for BCD adjustments |
Worked Example: Flag Analysis
Instruction: SUB AL, BL where AL=5, BL=7.
Steps:
AL - BL=FFh(unsigned underflow).- Flags set:
ZF=0(result ≠ 0),CF=1(unsigned overflow),SF=1(MSB=1, negative),OF=0(no signed overflow;5-7is within-128to127).
- Conditional jumps:
JC Labelwould execute (carry set).JS Labelwould execute (sign set).
Real-world tie-in:
- Ncell’s SIM authentication uses flag checks to validate user input (e.g.,
JZif PIN matches).
4. String Operations: Block Data Manipulation
The 8086 has dedicated string instructions (MOVSB, CMPSB, SCAS) that auto-increment SI/DI and support REP for loops.
4.1 String Instructions Table
| Instruction | Operation | Flags Affected | Example Use Case |
|---|---|---|---|
MOVSB |
[SI] → [DI]; SI++, DI++ |
None | Copy memory blocks |
CMPSB |
Compare [SI] and [DI] |
ZF, CF, SF, OF | Search/sort algorithms |
SCAS |
Compare [AL] with [DI] |
ZF, CF, SF, OF | Scan for a value in a buffer |
STOSB |
[AL] → [DI]; DI++ |
None | Fill memory with a value |
LODSB |
[SI] → AL; SI++ |
None | Load data into AL |
Worked Example: Search for a Character
Problem: Find 'x' in the string "abcxdef".
Solution:
DATA SEGMENT
STR DB 'abcxdef$'
TARGET DB 'x'
DATA ENDS
CODE SEGMENT
MOV AX, DATA
MOV DS, AX
LEA SI, STR ; SI = start of string
MOV AL, TARGET ; AL = 'x'
MOV CX, 6 ; Length of string
SEARCH_LOOP:
CMPSB ; Compare [SI] with AL; auto-increment SI
JZ FOUND ; Jump if ZF=1 (match found)
LOOP SEARCH_LOOP
JMP NOT_FOUND
FOUND:
; SI now points to 'x'
JMP EXIT
NOT_FOUND:
; Handle no-match case
EXIT:
CODE ENDS
Real-world tie-in:
- Daraz’s order processing uses
SCASto scan inventory lists for product IDs.
5. Loops and Conditional Jumps: Controlling Program Flow
Loops (LOOP, REP) and jumps (JZ, JC) are essential for repetitive tasks.
5.1 Loop Constructs
stateDiagram-v2
[*] --> LOOP_START
LOOP_START --> CHECK_CONDITION: CX != 0?
CHECK_CONDITION -->|Yes| EXECUTE_BLOCK
EXECUTE_BLOCK --> DECREMENT_CX: CX--
DECREMENT_CX --> LOOP_START
CHECK_CONDITION -->|No| [*]Worked Example: Sum of Array Elements
Problem: Sum numbers in ARR DB 1,2,3,4.
Solution:
DATA SEGMENT
ARR DB 1,2,3,4
LEN EQU $-ARR
DATA ENDS
CODE SEGMENT
MOV AX, DATA
MOV DS, AX
LEA SI, ARR ; SI = start of array
MOV CX, LEN ; CX = counter
MOV AX, 0 ; AX = sum (init)
SUM_LOOP:
ADD AL, [SI] ; Add current element to AL
INC SI ; Move to next element
LOOP SUM_LOOP ; Decrement CX; loop if CX!=0
CODE ENDS
Real-world tie-in:
- NTC’s electricity billing uses loops to sum consumption data from smart meters.
In the Real World
Khalti’s Payment Routing:
- Uses based indexed addressing (
[BX+SI]) to traverse a linked list of merchant transactions stored in memory. The CPU calculates the next transaction’s address dynamically, reducing memory access time.
- Uses based indexed addressing (
eSewa’s Transaction Validation:
- Employs string reversal (like the worked example) to validate user input (e.g., reversing a PIN and comparing it to a stored hash). Flags (
ZF) determine if the transaction is approved.
- Employs string reversal (like the worked example) to validate user input (e.g., reversing a PIN and comparing it to a stored hash). Flags (
Pathao’s Driver Matching:
- Uses loop constructs (
LOOP) to scan a list of nearby drivers (stored in[SI]) and conditional jumps (JZ) to match the closest driver based on distance data. TheCFflag helps handle overflow when calculating distances.
- Uses loop constructs (
Exam Tip
Addressing Modes:
- Always calculate the effective address (EA) for indirect modes (e.g.,
[BX+SI+10]). Exams often ask for EA values. - Common mistake: Forgetting to include the segment base (e.g.,
DS:prefix). WriteMOV AX, [BX]asMOV AX, DS:[BX]in full answers.
- Always calculate the effective address (EA) for indirect modes (e.g.,
Flags:
- For
ADD/SUB, list all 6 flags and justify each (e.g., "CF=1 because 9+7 > 255"). - Shortcut: Use the mnemonic "ZCSOAP" (Zero, Carry, Sign, Overflow, Auxiliary, Parity) to remember the flags.
- For
ALP Questions:
- String reversal: Show the initial and final states of
SI,DI, and memory. - Loops: Always initialize
CXand trace its decrement. - Conditional jumps: State the flag condition (e.g., "JZ jumps if ZF=1").
- String reversal: Show the initial and final states of
Worked Examples:
- Trace tables (like the string reversal example) are worth 50% of marks. Include columns for registers, flags, and memory.
- Label your code: Use comments like
; SI = start of arrayto explain non-obvious steps.
Past Exam Patterns:
- Part (a): Often asks for flag analysis or addressing mode calculations.
- Part (b): Almost always requires writing a program (e.g., reverse a string, find the greatest number). Start with a pseudocode plan before coding.
(Note: Highlights how SI/DI auto-increment and flags change.)
Based on the PU BE Computer (PU) syllabus for Microprocessor, unit 3.
Discussion
Loading…