PadhaikoAll subjects

Assembly Language Programming, Syntax & Directives

Microprocessors (ENEX 201)

Open in the Padhaiko app

3.6 Assembly language programming

A microprocessor can execute only machine language—binary bit patterns (0s and 1s) representing opcodes and operands. Writing and debugging large programs directly in binary or hexadecimal machine code is tedious and error-prone. Assembly language solves this by replacing binary opcodes with readable symbolic abbreviations called mnemonics (e.g., MOV, ADD, JMP) and replacing raw numeric memory addresses with symbolic names (labels and variable identifiers).

Definition

Assembly Language and Assembler

Why Assembly Language Is Still Taught and Used:

3.7 High level versus low level programming

Programming languages fall into low-level languages (machine language and assembly language, tied closely to hardware) and high-level languages (C, C++, Java, Python, designed for human readability and hardware independence).

AspectLow-Level Language (Assembly)High-Level Language (C / Python / Java)
Abstraction & ReadabilityMachine-oriented mnemonics, registers, and memory addresses; harder to readEnglish-like statements and mathematical expressions; easy to read and maintain
PortabilityMachine-dependent: 8086 assembly will not run on ARM or 8085Portable: same source compiles or runs across diverse CPU architectures
Hardware & Register AccessFull, direct access to CPU registers, flags, ports, and exact memory offsetsAbstracted away; hardware accessed only via OS drivers or inline assembly
Translator RequiredAssembler (1-to-1 instruction translation)Compiler or Interpreter (1-to-many machine instructions per statement)
Execution Speed & Code SizeVery fast execution and compact machine code when hand-tunedSlightly larger code and runtime overhead (depends on compiler optimization)
Development & Debugging TimeSlow to write and error-prone for large applicationsRapid development, strong type checking, and structured debugging
Typical ApplicationsBootloaders, BIOS/OS kernels, device drivers, real-time DSP/embedded controlDesktop/web apps, databases, compilers, scientific computing

3.8 Assembly language syntax

An 8086 assembler (following the standard Intel/MASM/TASM convention) parses each source line according to strict lexical rules for comments, reserved words, identifiers, statements, directives, operators, and instructions.

3.8.1 Comments

A comment documents the purpose of instructions, register usage, or algorithms for human readers and is completely ignored by the assembler during code generation.

Full-Line and Inline Comments in 8086 Assembly8086 ASM
; Program: Sum two 16-bit numbers in registers
MOV AX, 1234H    ; Load first operand into AX
MOV BX, 0010H    ; Load second operand into BX
ADD AX, BX       ; AX = AX + BX (result = 1244H)

3.8.2 Reserved words

Reserved words have predefined, fixed meanings to the 8086 assembler and cannot be used as user-defined identifiers (variable names or labels). They fall into five categories:

  1. Instruction Mnemonics: MOV, ADD, SUB, MUL, DIV, CMP, JMP, CALL, INT, LOOP, etc.
  2. Assembler Directives (Pseudo-ops): DB, DW, DD, DUP, EQU, ORG, SEGMENT, ENDS, ASSUME, PROC, ENDP, END, .MODEL, .DATA, .CODE, .STACK.
  3. Register Names: AX, AH, AL, BX, CX, DX, CS, DS, SS, ES, SP, BP, SI, DI, IP, FLAGS.
  4. Operators: OFFSET, SEG, PTR, TYPE, LENGTH, SIZE, BYTE, WORD, DWORD, SHORT, NEAR, FAR.
  5. Predefined Symbols: @DATA, @CODE, @STACK.

3.8.3 Identifiers

An identifier is a programmer-chosen symbolic name assigned to a variable, constant, procedure, segment, or branch label.

Definition

Rules for Forming Valid 8086 Identifiers (MASM/TASM)

  1. Permitted Characters: Letters (A–Z, a–z), digits (0–9), and the special symbols underscore (_), at-sign (@), question mark (?), and dollar sign (\$).
  2. Starting Character: Must begin with a letter or one of the allowed special symbols (_, @, ?, \$)—it cannot start with a digit (0–9). Note that a leading period (.) is reserved for directives such as .DATA.
  3. No Embedded Spaces or Punctuation: Spaces, commas, colons, semicolons, and arithmetic symbols (+, -) are illegal inside an identifier.
  4. Case Insensitivity: By default, MASM/TASM treat identifiers as case-insensitive (TOTAL, Total, and total refer to the same symbol).
  5. Length & Uniqueness: Classic assemblers recognize up to 31 significant characters; identifiers cannot match any reserved word and must be unique within their scope.
Valid vs. Invalid 8086 Identifiers
IdentifierValid?Reason
LOOP_1YesStarts with a letter; uses letters, underscore, and digit
@COUNTYesStarts with @ (valid non-digit start character)
2ND_VALNoBegins with a digit (2)
TOTAL SUMNoContains an embedded space
AXNoReserved CPU register name
SUM-1NoHyphen - is interpreted as subtraction operator

3.8.4 Statements

Every non-blank line in an 8086 source file is either an executable instruction statement (translated into machine code for the CPU) or a directive statement (commands executed by the assembler at assembly time). Each statement follows a four-field layout:

[Name / Label] Operation (Mnemonic or Directive) [Operand(s)] [; Comment]

3.8.5 Directives

Assembler directives (also called pseudo-instructions or pseudo-ops) are instructions to the assembler, not the 8086 processor. They generate no runtime machine opcodes; instead, they reserve memory, define constants, map segments, and mark program structure.

Essential 8086 Assembler Directives
CategoryDirectivePurpose & Example
Data DefinitionDBDefine Byte (1 byte per value/char): NUM DB 25H, MSG DB 'HI\$'
Data DefinitionDWDefine Word (2 bytes, little-endian): VAL DW 1234H
Data DefinitionDD / DQ / DTDefine Doubleword (4 B), Quadword (8 B), Tenbyte (10 B, packed BCD)
Data DefinitionDUPRepeat allocation: ARR DB 10 DUP(0) reserves 10 zero bytes; BUF DB 20 DUP(?) uninitialized
Segments (Full)SEGMENT / ENDSMarks start and end of a logical segment: DATA_SEG SEGMENT ... DATA_SEG ENDS
Segments (Full)ASSUMETells the assembler which segment register points to which segment: ASSUME CS:CODE_SEG, DS:DATA_SEG
Segments (Simple).MODELSelects memory model (TINY for .COM; SMALL = 1 code + 1 data segment <= 64 KB)
Segments (Simple).STACK, .DATA, .CODESimplified directives opening Stack (.STACK 100H), Data, and Code segments
Constants & OriginEQU / =Defines symbolic constants without allocating RAM (MAX EQU 50 cannot be redefined; N = 10 can)
Constants & OriginORGSets the assembler's Location Counter (LC) to a specific offset (e.g., ORG 100H for .COM files)
Procedures & EndPROC / ENDPWraps subroutines with NEAR (intra-segment) or FAR (inter-segment): READ PROC NEAR ... READ ENDP
Program EndEND [label]Stops assembly and optionally names the entry-point procedure (END MAIN)
MacrosMACRO / ENDMDefines a reusable inline code macro expanded during assembly

3.8.6 Operators

Operators perform computations or return attributes of symbols at assembly time (never at runtime unless combined with instructions).

Common 8086 Assembly Operators
GroupOperator(s)Meaning & Example
Arithmetic+, -, *, /, MOD, SHL, SHRConstant expression evaluation at assembly time (MOV AX, 10*4+2 -> MOV AX, 42)
LogicalAND, OR, XOR, NOTBitwise constant folding (MASK EQU 0FH AND 3CH)
RelationalEQ, NE, LT, GT, LE, GEEvaluate to FFFFH (true) or 0000H (false) in conditional assembly
AttributeOFFSETReturns 16-bit offset of a variable/label within its segment (MOV DX, OFFSET MSG)
AttributeSEGReturns 16-bit segment base address of a symbol (MOV AX, SEG MSG)
AttributePTROverrides operand size (BYTE PTR [BX], WORD PTR [SI]) or jump distance (FAR PTR)
AttributeTYPEReturns byte size of one element (DB -> 1, DW -> 2, DD -> 4, NEAR -> -1, FAR -> -2)
AttributeLENGTHReturns number of items created by DUP (1 if no DUP used)
AttributeSIZEReturns total bytes of a variable: SIZE = TYPE * LENGTH
Override: (Segment Override)Forces a non-default segment register (MOV AL, ES:[BX])

3.8.7 Instructions

Unlike directives, instructions are translated directly into binary machine opcodes and executed at runtime by the EU. The 8086 instruction set is organized into six functional groups:

  1. Data Transfer Instructions: Move bytes or words between registers, memory, stack, and I/O ports (MOV, PUSH, POP, XCHG, XLAT, IN, OUT, LEA, LDS, LES).
  2. Arithmetic Instructions: Perform binary and BCD arithmetic (ADD, ADC, INC, SUB, SBB, DEC, NEG, CMP, MUL, IMUL, DIV, IDIV, CBW, CWD, DAA, DAS, AAA, AAS, AAM, AAD).
  3. Bit Manipulation (Logical, Shift & Rotate) Instructions: AND, OR, XOR, NOT, TEST, SHL/SAL, SHR, SAR, ROL, ROR, RCL, RCR.
  4. String Instructions: High-speed block operations on DS:SI and ES:DI (MOVSB/MOVSW, CMPSB/CMPSW, SCASB/SCASW, LODSB/LODSW, STOSB/STOSW, with REP/REPE/REPNE).
  5. Program Execution Transfer (Branch) Instructions: Unconditional/conditional jumps, loops, calls, and interrupts (JMP, JE/JZ, JNE/JNZ, JC, JG, JL, LOOP, CALL, RET, INT, IRET).
  6. Processor Control Instructions: Flag manipulation and external synchronization (CLC, STC, CMC, CLD, STD, CLI, STI, HLT, WAIT, ESC, LOCK, NOP).
Example 1

1 (5 marks)

Determine the total bytes allocated in .DATA and the exact starting offset (Location Counter) of each variable in the following data segment:

Tracing Location Counter (LC) Starting at Offset 0000H:

  • FLAG DB 01H: Allocates 1 byte (0000H). Next LC = 0001H.
  • COUNT DW 1234H: Allocates 2 bytes (0001H–0002H, little-endian: 34H then 12H). Next LC = 0003H.
  • ARR DW 5 DUP(0): Allocates 5 * 2 = 10 bytes (0AH bytes, 0003H–000CH). Next LC = 000DH.
  • PTR_VAL DD 11223344H: Allocates 4 bytes (000DH–0010H). Next LC = 0011H.
  • TITLE_STR DB 'IOE86\$': 'I','O','E','8','6','\$' = 6 bytes (0011H–0016H). Next LC = 0017H.

Summary Table of Variable Offsets and Byte Sizes:

Allocated Offsets and Sizes
VariableDirectiveElement SizeCountTotal BytesOffset (LC)
FLAGDB1110000H
COUNTDW2120001H
ARRDW 5 DUP(0)25100003H
PTR_VALDD414000DH
TITLE_STRDB (string)1660011H

Total memory allocated = 1 + 2 + 10 + 4 + 6 = 23 bytes (17H bytes).

Answer:

Offsets are FLAG = 0000H, COUNT = 0001H, ARR = 0003H, PTR_VAL = 000DH, TITLE_STR = 0011H, and the total data segment allocation is 23 bytes (17H).

Example 2

2 (4 marks)

Given the data declarations below starting at offset 0000H:

8086 ASM
BYTE_VAR  DB 25H
WORD_ARR  DW 8 DUP(10H)
NEXT_VAR  DB 'A'

What values do the assembler operators TYPE WORD_ARR, LENGTH WORD_ARR, SIZE WORD_ARR, and OFFSET NEXT_VAR evaluate to, and what values enter AX, BX, and CL after executing MOV AX, OFFSET WORD_ARR, MOV BX, WORD_ARR, and MOV CL, BYTE PTR WORD_ARR?

Evaluating Assembly-Time Attribute Operators:

  • BYTE_VAR occupies 1 byte at offset 0000H, so WORD_ARR starts immediately at offset 0001H.
  • TYPE WORD_ARR = 2 (because WORD_ARR is defined with DW, 2 bytes per element).
  • LENGTH WORD_ARR = 8 (number of elements in 8 DUP(10H)).
  • SIZE WORD_ARR = TYPE * LENGTH = 2 * 8 = 16 (10H bytes, spanning 0001H–0010H).
  • OFFSET NEXT_VAR = 0001H + 10H = 0011H.

Tracing Register Values:

  • MOV AX, OFFSET WORD_ARR loads the 16-bit offset address 0001H into AX.
  • MOV BX, WORD_ARR reads the first 16-bit word stored at WORD_ARR (0010H) into BX.
  • MOV CL, BYTE PTR WORD_ARR overrides the WORD type of WORD_ARR to BYTE, reading only the low byte at 0001H (10H, little-endian low byte of 0010H) into CL.
Registers After Operator Instructions
AX0001H
BX0010H
CL10H
Answer:

TYPE WORD_ARR = 2, LENGTH WORD_ARR = 8, SIZE WORD_ARR = 16 (10H), OFFSET NEXT_VAR = 0011H, AX = 0001H, BX = 0010H, and CL = 10H.

Example 3

3 (5 marks)

(Institute of Engineering Exam Style) Write a complete 8086 assembly program that adds two 16-bit variables NUM1 = 1200H and NUM2 = 0350H and stores the result in SUM, showing how the program is structured using full segment directives (SEGMENT, ENDS, ASSUME).

Full-Segment Program Structure:

8086 Program Using Full Segment Directives8086 ASM
DATA_SEG SEGMENT
    NUM1 DW 1200H
    NUM2 DW 0350H
    SUM  DW ?
DATA_SEG ENDS

CODE_SEG SEGMENT
    ASSUME CS:CODE_SEG, DS:DATA_SEG
START:
    MOV AX, DATA_SEG    ; Load segment base of DATA_SEG into AX
    MOV DS, AX          ; Initialize DS register

    MOV AX, NUM1        ; AX = 1200H
    ADD AX, NUM2        ; AX = 1200H + 0350H = 1550H
    MOV SUM, AX         ; Store result 1550H into SUM

    MOV AH, 4CH         ; DOS terminate function
    INT 21H
CODE_SEG ENDS
    END START

Register & Memory Result: After ADD AX, NUM2 and MOV SUM, AX, AX = 1550H and [SUM] = 1550H (50H at low byte, 15H at high byte).

Answer:

The program defines DATA_SEG (SEGMENT/ENDS) and CODE_SEG (ASSUME CS:CODE_SEG, DS:DATA_SEG), initializes DS through AX, computes SUM = 1200H + 0350H = 1550H, and exits via INT 21H (AH=4CH) before END START.

Exercises

Question 1

Differentiate between high-level and low-level programming languages across at least five criteria, and explain why assembly language is still used in systems programming.

Comparison Criteria:

  1. Abstraction: Low-level assembly uses CPU-specific mnemonics and registers; high-level languages use human-readable algebraic/control constructs.
  2. Portability: Assembly is non-portable (tied to one CPU ISA like 8086); high-level source code is portable across platforms with recompilation.
  3. Hardware Control: Assembly directly accesses registers, flags, physical segments, and ports; high-level languages rely on OS/compiler abstractions.
  4. Translation: Assembly uses a 1-to-1 assembler; high-level uses a compiler or interpreter (1-to-many).
  5. Speed & Code Size: Well-written assembly achieves minimal memory footprint and deterministic timing; high-level trades slight overhead for rapid development and maintainability.

Role in Systems Programming: Bootloaders, BIOS routines, interrupt service routines (ISRs), and hardware device drivers require exact register control, atomic/privileged CPU instructions (CLI, STI, IN, OUT, IRET), and cycle-predictable timing that only assembly provides cleanly.

Answer:

Low-level assembly trades portability and ease of writing for direct hardware control, 1-to-1 translation, minimal code size, and maximum speed—making it essential for bootloaders, ISRs, and low-level drivers.

Question 2

State the four fields of an 8086 assembly statement and list the rules for forming valid user-defined identifiers. Classify MY_DATA, 3SUM, MOV, and @LOOP as valid or invalid identifiers.

Four Statement Fields:

  1. Name / Label Field (optional; code labels end with :, data/directive names do not).
  2. Operation Field (required; CPU mnemonic or assembler directive).
  3. Operand Field (zero, one, or two operands; destination, source).
  4. Comment Field (optional; starts with ;).

Identifier Rules & Classification: Rules: Must contain only letters, digits, _, @, ?, \$; cannot start with a digit; cannot contain spaces; cannot be a reserved word; case-insensitive.

  • MY_DATA: Valid (starts with letter, uses underscore).
  • 3SUM: Invalid (starts with a digit 3).
  • MOV: Invalid (reserved instruction mnemonic).
  • @LOOP: Valid (starts with permitted symbol @).
Answer:

Fields: [Label] Operation [Operands] [; Comment]. Valid: MY_DATA, @LOOP; Invalid: 3SUM (starts with digit), MOV (reserved mnemonic).

Question 3

What are assembler directives? Explain the function of DB, DW, DUP, EQU, ASSUME, ORG, and END with a short example of each.

Assembler Directives Definition: Directives (pseudo-ops) are commands given to the assembler at assembly time to allocate memory, define constants, assign segments, and control assembly flow; they generate no CPU opcodes.

Functions and Examples:

  • DB (Define Byte): Reserves 1-byte items (VAL DB 45H).
  • DW (Define Word): Reserves 2-byte words (TOTAL DW 1234H).
  • DUP (Duplicate): Repeats memory allocation (BUF DB 20 DUP(0)).
  • EQU (Equate): Assigns a symbolic constant without allocating RAM (LIMIT EQU 100).
  • ASSUME: Associates segment registers with logical segment names (ASSUME CS:CODE, DS:DATA).
  • ORG (Origin): Sets the assembler location counter (ORG 100H).
  • END: Terminates source assembly and optionally sets entry label (END MAIN).
Answer:

Assembler directives instruct the assembler rather than the CPU: DB/DW/DUP allocate data, EQU defines constants, ASSUME maps segment registers, ORG sets the location counter, and END ends the module.

Question 4

Given the data declarations starting at offset 0000H: BYTE_A DB 0FFH TABLE DW 4 DUP(1234H) TEXT DB 'MICRO-8086', 0DH, 0AH Compute TYPE TABLE, LENGTH TABLE, SIZE TABLE, OFFSET TEXT, and the total number of bytes allocated.

Evaluating TABLE Attributes:

  • TABLE is declared with DW (2 bytes per element), so TYPE TABLE = 2.
  • 4 DUP(1234H) creates 4 elements, so LENGTH TABLE = 4.
  • SIZE TABLE = TYPE * LENGTH = 2 * 4 = 8 bytes (08H).

Computing OFFSET TEXT and Total Bytes:

  • BYTE_A occupies 1 byte at 0000H.
  • TABLE occupies 8 bytes from 0001H to 0008H.
  • Therefore OFFSET TEXT = 0009H.
  • 'MICRO-8086' has 10 characters plus 0DH and 0AH = 12 bytes (0009H–0014H).
  • Total bytes allocated = 1 + 8 + 12 = 21 bytes (15H).
Answer:

TYPE TABLE = 2, LENGTH TABLE = 4, SIZE TABLE = 8, OFFSET TEXT = 0009H, and total allocated size = 21 bytes.

Question 5

Why does the instruction MOV [SI], 10H fail to assemble in 8086 MASM/TASM, and how do you fix it? Also explain the difference between MOV BX, OFFSET ARR and MOV BX, ARR.

Resolving MOV [SI], 10H:

  • [SI] is an untyped memory pointer and 10H is an immediate constant that fits in either 8 bits (10H) or 16 bits (0010H). The assembler cannot tell whether to generate an 8-bit or 16-bit memory write opcode.
  • Fix: Specify the size explicitly with the PTR operator: MOV BYTE PTR [SI], 10H (writes 1 byte) or MOV WORD PTR [SI], 10H (writes 2 bytes).

OFFSET ARR vs. ARR:

  • MOV BX, OFFSET ARR moves the 16-bit offset address of ARR into BX (immediate addressing, equivalent to LEA BX, ARR for static variables).
  • MOV BX, ARR reads the 16-bit data value stored inside memory at ARR into BX (direct memory addressing).
Answer:

MOV [SI], 10H is ambiguous in operand size and must be written with BYTE PTR or WORD PTR. MOV BX, OFFSET ARR loads the address of ARR, whereas MOV BX, ARR loads the contents stored at ARR.

Past exam questions for Microprocessors

← Segment:Offset Addressing, Pins & Addressing ModesEXE vs COM, Assembling/Linking, One- & Two-Pass Assemblers →