Assembly Language Programming, Syntax & Directives
Open in the Padhaiko app3.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).
Assembly Language and Assembler
- Assembly Language: A low-level, processor-specific programming language that has a one-to-one correspondence with the CPU's machine instructions (each assembly instruction translates to one machine instruction), supplemented by assembler directives for memory layout and constants.
- Assembler: A system translator program (such as MASM, TASM, or NASM for 8086) that reads an assembly source file (
.asm) and converts it into binary object code (.obj) or executable machine code.
Why Assembly Language Is Still Taught and Used:
- Direct Hardware Control: Programs can directly manipulate CPU registers, flags, memory segments, interrupt vectors, and I/O ports.
- Maximum Speed & Minimal Footprint: Critical inner loops, bootloaders, interrupt service routines (ISRs), and real-time embedded firmware execute without compiler overhead.
- Architectural Understanding: Writing 8086 assembly makes bus cycles, memory segmentation, stack frames, and addressing modes concrete.
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).
| Aspect | Low-Level Language (Assembly) | High-Level Language (C / Python / Java) |
|---|---|---|
| Abstraction & Readability | Machine-oriented mnemonics, registers, and memory addresses; harder to read | English-like statements and mathematical expressions; easy to read and maintain |
| Portability | Machine-dependent: 8086 assembly will not run on ARM or 8085 | Portable: same source compiles or runs across diverse CPU architectures |
| Hardware & Register Access | Full, direct access to CPU registers, flags, ports, and exact memory offsets | Abstracted away; hardware accessed only via OS drivers or inline assembly |
| Translator Required | Assembler (1-to-1 instruction translation) | Compiler or Interpreter (1-to-many machine instructions per statement) |
| Execution Speed & Code Size | Very fast execution and compact machine code when hand-tuned | Slightly larger code and runtime overhead (depends on compiler optimization) |
| Development & Debugging Time | Slow to write and error-prone for large applications | Rapid development, strong type checking, and structured debugging |
| Typical Applications | Bootloaders, BIOS/OS kernels, device drivers, real-time DSP/embedded control | Desktop/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.
- Every comment begins with a semicolon (
;) and extends to the end of that line. - A semicolon at column 1 creates a full-line comment; a semicolon after an instruction or directive creates an inline comment.
; 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:
- Instruction Mnemonics:
MOV,ADD,SUB,MUL,DIV,CMP,JMP,CALL,INT,LOOP, etc. - Assembler Directives (Pseudo-ops):
DB,DW,DD,DUP,EQU,ORG,SEGMENT,ENDS,ASSUME,PROC,ENDP,END,.MODEL,.DATA,.CODE,.STACK. - Register Names:
AX,AH,AL,BX,CX,DX,CS,DS,SS,ES,SP,BP,SI,DI,IP,FLAGS. - Operators:
OFFSET,SEG,PTR,TYPE,LENGTH,SIZE,BYTE,WORD,DWORD,SHORT,NEAR,FAR. - 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.
Rules for Forming Valid 8086 Identifiers (MASM/TASM)
- Permitted Characters: Letters (
A–Z,a–z), digits (0–9), and the special symbols underscore (_), at-sign (@), question mark (?), and dollar sign (\$). - 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. - No Embedded Spaces or Punctuation: Spaces, commas, colons, semicolons, and arithmetic symbols (
+,-) are illegal inside an identifier. - Case Insensitivity: By default, MASM/TASM treat identifiers as case-insensitive (
TOTAL,Total, andtotalrefer to the same symbol). - Length & Uniqueness: Classic assemblers recognize up to 31 significant characters; identifiers cannot match any reserved word and must be unique within their scope.
| Identifier | Valid? | Reason |
|---|---|---|
LOOP_1 | Yes | Starts with a letter; uses letters, underscore, and digit |
@COUNT | Yes | Starts with @ (valid non-digit start character) |
2ND_VAL | No | Begins with a digit (2) |
TOTAL SUM | No | Contains an embedded space |
AX | No | Reserved CPU register name |
SUM-1 | No | Hyphen - 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]
- Name / Label Field (Optional): Identifies a memory address or symbol. Code labels inside
.CODEend with a colon (:) (e.g.,NEXT:); data variable names and procedure/segment names do not use a colon (e.g.,COUNT DB 05H,MAIN PROC). - Operation Field (Required): Either a CPU instruction mnemonic (
MOV) or an assembler directive (DB,EQU). - Operand Field (Zero, One, or Two Operands): Specifies data, registers, memory variables, or expressions. Two-operand 8086 instructions always place the destination first and the source second (
MOV destination, source). - Comment Field (Optional): Begins with
;.
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.
| Category | Directive | Purpose & Example |
|---|---|---|
| Data Definition | DB | Define Byte (1 byte per value/char): NUM DB 25H, MSG DB 'HI\$' |
| Data Definition | DW | Define Word (2 bytes, little-endian): VAL DW 1234H |
| Data Definition | DD / DQ / DT | Define Doubleword (4 B), Quadword (8 B), Tenbyte (10 B, packed BCD) |
| Data Definition | DUP | Repeat allocation: ARR DB 10 DUP(0) reserves 10 zero bytes; BUF DB 20 DUP(?) uninitialized |
| Segments (Full) | SEGMENT / ENDS | Marks start and end of a logical segment: DATA_SEG SEGMENT ... DATA_SEG ENDS |
| Segments (Full) | ASSUME | Tells the assembler which segment register points to which segment: ASSUME CS:CODE_SEG, DS:DATA_SEG |
| Segments (Simple) | .MODEL | Selects memory model (TINY for .COM; SMALL = 1 code + 1 data segment <= 64 KB) |
| Segments (Simple) | .STACK, .DATA, .CODE | Simplified directives opening Stack (.STACK 100H), Data, and Code segments |
| Constants & Origin | EQU / = | Defines symbolic constants without allocating RAM (MAX EQU 50 cannot be redefined; N = 10 can) |
| Constants & Origin | ORG | Sets the assembler's Location Counter (LC) to a specific offset (e.g., ORG 100H for .COM files) |
| Procedures & End | PROC / ENDP | Wraps subroutines with NEAR (intra-segment) or FAR (inter-segment): READ PROC NEAR ... READ ENDP |
| Program End | END [label] | Stops assembly and optionally names the entry-point procedure (END MAIN) |
| Macros | MACRO / ENDM | Defines 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).
| Group | Operator(s) | Meaning & Example |
|---|---|---|
| Arithmetic | +, -, *, /, MOD, SHL, SHR | Constant expression evaluation at assembly time (MOV AX, 10*4+2 -> MOV AX, 42) |
| Logical | AND, OR, XOR, NOT | Bitwise constant folding (MASK EQU 0FH AND 3CH) |
| Relational | EQ, NE, LT, GT, LE, GE | Evaluate to FFFFH (true) or 0000H (false) in conditional assembly |
| Attribute | OFFSET | Returns 16-bit offset of a variable/label within its segment (MOV DX, OFFSET MSG) |
| Attribute | SEG | Returns 16-bit segment base address of a symbol (MOV AX, SEG MSG) |
| Attribute | PTR | Overrides operand size (BYTE PTR [BX], WORD PTR [SI]) or jump distance (FAR PTR) |
| Attribute | TYPE | Returns byte size of one element (DB -> 1, DW -> 2, DD -> 4, NEAR -> -1, FAR -> -2) |
| Attribute | LENGTH | Returns number of items created by DUP (1 if no DUP used) |
| Attribute | SIZE | Returns 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:
- 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). - 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). - Bit Manipulation (Logical, Shift & Rotate) Instructions:
AND,OR,XOR,NOT,TEST,SHL/SAL,SHR,SAR,ROL,ROR,RCL,RCR. - String Instructions: High-speed block operations on
DS:SIandES:DI(MOVSB/MOVSW,CMPSB/CMPSW,SCASB/SCASW,LODSB/LODSW,STOSB/STOSW, withREP/REPE/REPNE). - 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). - Processor Control Instructions: Flag manipulation and external synchronization (
CLC,STC,CMC,CLD,STD,CLI,STI,HLT,WAIT,ESC,LOCK,NOP).
1
Determine the total bytes allocated in .DATA and the exact starting offset (Location Counter) of each variable in the following data segment:
FLAG DB 01HCOUNT DW 1234HARR DW 5 DUP(0)PTR_VAL DD 11223344HTITLE_STR DB 'IOE86\$'
Tracing Location Counter (LC) Starting at Offset 0000H:
FLAG DB 01H: Allocates1 byte(0000H). NextLC = 0001H.COUNT DW 1234H: Allocates2 bytes(0001H–0002H, little-endian:34Hthen12H). NextLC = 0003H.ARR DW 5 DUP(0): Allocates5 * 2 = 10 bytes(0AHbytes,0003H–000CH). NextLC = 000DH.PTR_VAL DD 11223344H: Allocates4 bytes(000DH–0010H). NextLC = 0011H.TITLE_STR DB 'IOE86\$':'I','O','E','8','6','\$'=6 bytes(0011H–0016H). NextLC = 0017H.
Summary Table of Variable Offsets and Byte Sizes:
| Variable | Directive | Element Size | Count | Total Bytes | Offset (LC) |
|---|---|---|---|---|---|
FLAG | DB | 1 | 1 | 1 | 0000H |
COUNT | DW | 2 | 1 | 2 | 0001H |
ARR | DW 5 DUP(0) | 2 | 5 | 10 | 0003H |
PTR_VAL | DD | 4 | 1 | 4 | 000DH |
TITLE_STR | DB (string) | 1 | 6 | 6 | 0011H |
Total memory allocated = 1 + 2 + 10 + 4 + 6 = 23 bytes (17H bytes).
Offsets are FLAG = 0000H, COUNT = 0001H, ARR = 0003H, PTR_VAL = 000DH, TITLE_STR = 0011H, and the total data segment allocation is 23 bytes (17H).
2
Given the data declarations below starting at offset 0000H:
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_VARoccupies 1 byte at offset0000H, soWORD_ARRstarts immediately at offset0001H.TYPE WORD_ARR = 2(becauseWORD_ARRis defined withDW, 2 bytes per element).LENGTH WORD_ARR = 8(number of elements in8 DUP(10H)).SIZE WORD_ARR = TYPE * LENGTH = 2 * 8 = 16(10Hbytes, spanning0001H–0010H).OFFSET NEXT_VAR = 0001H + 10H = 0011H.
Tracing Register Values:
MOV AX, OFFSET WORD_ARRloads the 16-bit offset address0001HintoAX.MOV BX, WORD_ARRreads the first 16-bit word stored atWORD_ARR(0010H) intoBX.MOV CL, BYTE PTR WORD_ARRoverrides theWORDtype ofWORD_ARRtoBYTE, reading only the low byte at0001H(10H, little-endian low byte of0010H) intoCL.
TYPE WORD_ARR = 2, LENGTH WORD_ARR = 8, SIZE WORD_ARR = 16 (10H), OFFSET NEXT_VAR = 0011H, AX = 0001H, BX = 0010H, and CL = 10H.
3
(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:
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 STARTRegister & Memory Result: After ADD AX, NUM2 and MOV SUM, AX, AX = 1550H and [SUM] = 1550H (50H at low byte, 15H at high byte).
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
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:
- Abstraction: Low-level assembly uses CPU-specific mnemonics and registers; high-level languages use human-readable algebraic/control constructs.
- Portability: Assembly is non-portable (tied to one CPU ISA like 8086); high-level source code is portable across platforms with recompilation.
- Hardware Control: Assembly directly accesses registers, flags, physical segments, and ports; high-level languages rely on OS/compiler abstractions.
- Translation: Assembly uses a 1-to-1 assembler; high-level uses a compiler or interpreter (1-to-many).
- 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.
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.
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:
- Name / Label Field (optional; code labels end with
:, data/directive names do not). - Operation Field (required; CPU mnemonic or assembler directive).
- Operand Field (zero, one, or two operands;
destination, source). - 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 digit3).MOV: Invalid (reserved instruction mnemonic).@LOOP: Valid (starts with permitted symbol@).
Fields: [Label] Operation [Operands] [; Comment]. Valid: MY_DATA, @LOOP; Invalid: 3SUM (starts with digit), MOV (reserved mnemonic).
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).
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.
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:
TABLEis declared withDW(2 bytes per element), soTYPE TABLE = 2.4 DUP(1234H)creates 4 elements, soLENGTH TABLE = 4.SIZE TABLE = TYPE * LENGTH = 2 * 4 = 8bytes (08H).
Computing OFFSET TEXT and Total Bytes:
BYTE_Aoccupies1 byteat0000H.TABLEoccupies8 bytesfrom0001Hto0008H.- Therefore
OFFSET TEXT = 0009H. 'MICRO-8086'has 10 characters plus0DHand0AH=12 bytes(0009H–0014H).- Total bytes allocated =
1 + 8 + 12 = 21 bytes(15H).
TYPE TABLE = 2, LENGTH TABLE = 4, SIZE TABLE = 8, OFFSET TEXT = 0009H, and total allocated size = 21 bytes.
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 and10His 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
PTRoperator:MOV BYTE PTR [SI], 10H(writes 1 byte) orMOV WORD PTR [SI], 10H(writes 2 bytes).
OFFSET ARR vs. ARR:
MOV BX, OFFSET ARRmoves the 16-bit offset address ofARRintoBX(immediate addressing, equivalent toLEA BX, ARRfor static variables).MOV BX, ARRreads the 16-bit data value stored inside memory atARRintoBX(direct memory addressing).
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.