IT236 Microprocessor and Computer Architecture

Microprocessor and Computer ArchitectureUnit 1011 min read

Assembly Language: Syntax, Instructions, Debugging & Real-World Apps

Unit 10 of Microprocessor and Computer Architecture covers assembly language programming fundamentals—syntax, instruction formats, memory addressing, debugging, and practical applications using 8086/8085 assembly, with direct ties to real-world systems like eSewa’s transaction validation and Ncell’s billing logic.

Core Concepts

1. What is Assembly Language?

Assembly language is a low-level programming language that uses mnemonics (human-readable abbreviations) to represent machine code instructions directly executed by the microprocessor. It is processor-specific (e.g., 8086, ARM) and requires an assembler to convert it into binary.

Why learn it?

  • Direct control over hardware (registers, memory, I/O).
  • Used in embedded systems, operating system kernels, and performance-critical applications.
  • Foundation for understanding high-level languages (C, Python) and compiler design.

Key Components of Assembly Language

1. Syntax Rules

Assembly programs follow strict syntax:

  • Labels: End with : (e.g., START:).
  • Instructions: Mnemonics like MOV, ADD, JMP.
  • Operands: Registers (AX, BX), memory ([SI]), or constants (5).
  • Comments: Start with ; (e.g., ; Add two numbers).

Example (8086 Assembly):

MOV AL, 5       ; Load 5 into AL register
MOV BL, 10      ; Load 10 into BL register
ADD AL, BL      ; Add BL to AL (AL = 15)

2. Instruction Formats

Assembly instructions follow three address formats:

Format Example Description
0-Address INC AX Implicit operand (e.g., increment AX).
1-Address MOV AX, 100 One operand (destination).
2-Address ADD AX, BX Two operands (source + destination).
3-Address (Not in 8086) Three operands (e.g., ADD AX, BX, CX).

Visual: 8086 Instruction Fields (Opcode defines the instruction; Mod/RM specifies registers/memory.)


Memory Addressing Modes

Assembly uses 8 addressing modes to access data. Here are the most critical ones:

Mode Example Description Use Case
Immediate MOV AX, 5 Data is part of the instruction. Loading constants.
Register MOV AX, BX Operand is a register. Fast arithmetic.
Direct MOV AX, [1000H] Memory address is given. Accessing fixed memory locations.
Register Indirect MOV AX, [BX] Address is in a register. Dynamic memory access.
Based Indexed MOV AX, [BX+SI] Sum of two registers. Array traversal.
Relative JMP NEXT Offset from IP (Instruction Pointer). Loops/jumps.

Worked Example: Calculating Loan EMI (Like Nabil Bank) Problem: Compute Equated Monthly Installment (EMI) for a loan using the formula: where:

  • (principal),
  • (monthly interest rate),
  • (months).

Assembly Code (8086):

MOV AX, 1000000   ; Load principal (P)
MOV BX, 60        ; Load months (n)
MOV CX, 5         ; Load annual rate (5%) → monthly rate = 5/1200 = 0.004166 (simplified to 0.005 for demo)
; Calculate numerator: P * r * (1 + r)^n
; (Simplified: Assume precomputed (1+r)^n = 1.34885)
MOV DX, 134885    ; (1 + r)^n ≈ 1.34885 (scaled to integer)
MUL DX           ; AX = P * (1 + r)^n
MOV SI, AX        ; Store in SI
; Calculate denominator: (1 + r)^n - 1
SUB SI, 1
; Final EMI = (P * r * (1 + r)^n) / denominator
MOV AX, 5000      ; P * r ≈ 5,000 (simplified)
MUL SI            ; AX = numerator * r
MOV BX, SI        ; Denominator
DIV BX            ; AX = EMI (result in AX)

Real-World Tie: Banks like Nabil Bank or Global IME use similar arithmetic in their loan processing systems, often optimized in assembly for speed.


Control Structures in Assembly

1. Conditional Jumps

Used for decision-making (like if-else in C). Examples:

  • JZ label (Jump if Zero)
  • JNZ label (Jump if Not Zero)
  • JMP label (Unconditional jump)

Example: Check if a number is even/odd

MOV AL, 7
AND AL, 1       ; Bitwise AND with 1
JZ EVEN         ; If AL=0, jump to EVEN
; Odd case
JMP ODDS
EVEN:           ; Label for even
MOV BL, 0
JMP END
ODDS:           ; Label for odd
MOV BL, 1
END:

2. Loops

LOOP instruction decrements CX and jumps if CX ≠ 0. Example: Sum first 10 numbers

MOV CX, 10      ; Counter
MOV AX, 0       ; Sum
MOV BX, 1       ; Start from 1
LOOP_START:
ADD AX, BX      ; Add BX to AX
INC BX          ; Increment BX
LOOP LOOP_START ; Repeat if CX > 0

Input/Output in Assembly

0481215AH8 bitsAL8 bits
DOS interrupt 21H AH=09H function call format (display string)

1. Using Ports (Hardware I/O)

Microprocessors communicate with peripherals via ports (e.g., IN/OUT instructions in 8086). Example: Read from port 60H (keyboard)

IN AL, 60H      ; Read from port 60H (keyboard data)

2. Displaying Output (DOS Functions)

In DOS-based assembly, use interrupt 21H for output. Example: Print "Hello"

MOV AH, 09H     ; DOS function to print string
MOV DX, OFFSET MSG
INT 21H         ; Call DOS interrupt
MSG DB 'Hello$'  ; String ends with '$'

Debugging Assembly Programs

1. Common Errors

Error Cause Fix
Syntax Error Invalid instruction (e.g., MOVX) Check manual for valid mnemonics.
Undefined Label Label not defined before use. Define labels before referencing.
Segmentation Fault Accessing invalid memory. Check segment registers (CS, DS).
Infinite Loop LOOP condition never met. Verify CX initialization.

2. Debugging Tools

  • Debug.com (DOS debugger)
  • OLYDBG (Windows)
  • GDB (Linux for assembly debugging)

Example Debug Session (8086):

  1. Assemble with TASM:
    TASM PROG.ASM
    TLINK PROG.OBJ
    
  2. Run in debugger:
    DEBUG PROG.EXE
    
  3. Step through instructions with T (trace) or P (proceed).

In the Real World

  1. eSewa Transaction Validation
    • Idea Used: Bitwise operations (e.g., AND, OR) to validate transaction IDs and checksums.
    • How: eSewa’s backend uses assembly-optimized checksum calculations to detect fraudulent transactions in real time.
Encrypted DataTransaction RequestAuthenticationAuthorizationBank ServerPOS TerminalCustomer DevicePayment Gateway
Real-world eSewa/Ncell payment processing flow using assembly-level I/O operations
  1. Ncell Billing System

    • Idea Used: Loops and arithmetic for calculating call durations, data usage, and billing cycles.
    • How: The billing engine processes millions of call records daily using optimized assembly routines for speed.
  2. Pathao Driver Routing

    • Idea Used: Memory addressing (e.g., [BX+SI]) to access dynamic route data from GPS coordinates.
    • How: Pathao’s real-time routing algorithm uses assembly for low-latency access to map data stored in memory buffers.
  3. NEPSE Stock Exchange Matching Engine

    • Idea Used: Conditional jumps (JZ, JNZ) to match buy/sell orders in microseconds.
    • How: High-frequency trading systems use assembly for order matching to minimize latency.

Assembly vs. High-Level Languages

Feature Assembly High-Level (C/Python)
Execution Speed Fastest (direct hardware control) Slower (compiler overhead)
Portability Non-portable (processor-specific) Portable (runs on any OS)
Code Size Compact (fewer instructions) Larger (compiled to many instructions)
Debugging Harder (low-level errors) Easier (high-level tools)
Use Case Embedded systems, OS kernels General-purpose applications

Exam Tip

  1. Focus on 8086 Assembly:

    • Know all 8 addressing modes and when to use them.
    • Practice arithmetic operations (e.g., ADD, SUB, MUL, DIV).
    • Memorize common DOS interrupts (INT 21H for I/O).
  2. Worked Examples Are Key:

    • Expect 2-3 marks on problems like:
      • Calculating factorial using loops.
      • Swapping two numbers without a temporary variable.
      • Converting binary to decimal.
  3. Debugging Questions:

    • Given a buggy assembly code, identify the error (e.g., wrong register, missing INT 21H).
    • Example:
      MOV AX, 5    ; Correct
      MOV BX, AX   ; Correct
      ADD AX, BX   ; Bug: AX = 10 (should be 5 + 5 = 10, but if AX was modified earlier, it’s wrong)
      
      Fix: Ensure registers are initialized properly.
  4. Real-World Applications:

    • Relate loops to billing systems (Ncell), bitwise ops to eSewa, and I/O to hardware interfaces (printers, keyboards).
    • Example question: "How would you optimize an assembly loop to calculate the total bill for 1000 Pathao rides?" Answer: Use REP (repeat) instructions or unrolled loops for speed.

Practice Problems

  1. Write an assembly program to find the GCD of two numbers using the Euclidean algorithm.
  2. Explain how JMP vs CALL differs in assembly.
  3. Debug the following code (find the error):
    MOV AL, 5
    ADD AL, 10
    MOV BL, AL  ; Error: BL is 15, but expected 10 (overwrite issue)
    SUB AL, 5
    
  4. How would you display "Hello, Nepal!" using DOS interrupt INT 21H?

Summary Checklist

  • Understand assembly syntax (labels, instructions, comments).
  • Master 8 addressing modes and their use cases.
  • Practice arithmetic, loops, and conditional jumps.
  • Know DOS I/O (INT 21H) and port I/O (IN/OUT).
  • Relate concepts to real-world systems (banks, eSewa, Ncell).
  • Be ready for debugging and optimization questions.

8086 microprocessor pinout diagramLabelled diagram showing pins for data bus, address bus, and control signals. (Image: lamfe, CC0, via Wikimedia Commons)

sequenceDiagram
    participant User
    participant Assembler
    participant Linker
    participant Loader
    participant CPU

    User->>Assembler: PROG.ASM (Source Code)
    Assembler->>Assembler: Converts to .OBJ (Object Code)
    Assembler->>Linker: .OBJ File
    Linker->>Linker: Resolves External References
    Linker->>Loader: .EXE File
    Loader->>CPU: Loads into Memory
    CPU->>CPU: Executes Instructions
    note right of CPU: CPU executes machine code
    note left of Assembler: Assembler translates assembly to object code
FetchInstruction Pointer (IP)DecodeOpcode/OperandExecuteALU/RegistersMemory AccessMemory (if needed)WritebackResult
Stages of instruction execution pipeline in x86 architecture (fetch-decode-execute-memory-writeback)

Based on the TU BIM syllabus for Microprocessor and Computer Architecture (IT236), unit 10.

Discussion

Loading…