0. Tools: NASM vs MASM vs EMU8086

CriterionNASMMASMEMU8086
Full nameNetwide AssemblerMicrosoft Macro Assembler8086 Microprocessor Emulator
Main purposeAssemble x86 sourceAssemble Microsoft-style x86 sourceTeach & simulate 8086 programs
CPU simulationNoNoYes
Visual debuggerNoThrough external Microsoft toolsYes
Register/flag displayNeeds a debugger/emulatorNeeds a debuggerBuilt in
8086 supportExcellentHistorically excellentDesigned specifically for 8086
macOSExcellentPoorNo native version
WindowsExcellentExcellentYes
LinuxExcellentNo native supportNo native support
LicenseFree, open sourceIncluded with Microsoft toolsProprietary trial/commercial
SyntaxClear, relatively simplePowerful but directive-heavyMASM-like + proprietary extensions
Best useCourse standard, portable projectsWindows/Microsoft developmentBeginner demos
Peripheral simulationNoNoLimited simulated devices
Proteus integrationPossible (binary/HEX output)Possible (output files)Not a primary workflow

The course uses NASM. NASM is only an assembler: to see registers and flags you need a debugger or emulator (for example DOSBox-X).


1. How the 8086 operates

1.1 From a problem to a running program

Application level: Problem statement → Algorithm → High-level language (e.g. C) → Compiler output
Machine level: 8086 assembly source → Assembler output (machine code) → Loader places code in memory → CPU fetches and executes instructions

Example: Total = a + b; becomes

mov ax, [a]
add ax, [b]
mov [total], ax

1.2 Stored-program computer

  • Instructions and data share the same memory system.
  • A program is a set of encoded instructions stored in memory.
  • The processor repeatedly reads an instruction, interprets its operation and operands, performs it, and advances to the next instruction, unless control flow changes (jump, call, ret, interrupt).
  • The same memory can hold instructions, variables, constants, and stack data.

1.3 CPU and memory communication

BusRole8086 width
Address busCPU places the address of the required memory location20 bits, so 2²⁰ = 1,048,576 bytes (1 MB) addressable
Data busCarries instruction or data values16 bits (external)
Control signalsIndicate memory read, memory write, or I/O operation—

1.4 Instruction cycle

Fetch (gets the next instruction):

  1. Form the address from CS and IP (CS:IP).
  2. The Bus Interface Unit (BIU) reads instruction bytes from memory.
  3. The bytes enter the 6-byte prefetch queue.
  4. The Execution Unit (EU) takes instruction bytes from the queue.
  5. IP advances to the following instruction.

Decode and execute (the EU interprets and performs it):

  • Control circuitry identifies the operation and the operand locations.
  • If a memory operand is needed, the EU asks the BIU for a bus operation.
  • The ALU performs arithmetic/logic.
  • The result is written to a register or memory, and the relevant flags are updated.

1.5 Conceptual (generic) CPU registers vs 8086

Generic modelMeaning8086 equivalent
MAR (Memory Address Register)Holds a memory addressConceptual, not accessible to programs
MBR / MDR (Memory Buffer/Data Register)Holds the transferred dataConceptual, not accessible
IR (Instruction Register)Holds the current instructionInternal
PC (Program Counter)Identifies the next instructionIP (combined with CS)
ALUOperates on temporary dataALU in the EU
—Status/control infoFLAGS

1.6 Register Transfer Language (RTL)

A compact notation to describe internal operations. It describes meaning, not assembler syntax.

  • [AX] = contents of AX
  • M[address] = contents of a memory location
  • ← = the destination receives a value
[AX] ← 4
[AX] ← [AX] + M[value]
M[result] ← [AX]

1.7 Instruction fields

  • Opcode (operation): tells the processor what to do (MOV, ADD, SUB, CMP, JMP…).
  • Operands: source and destination. They can be registers, memory locations, or immediate constants.
  • The encoded instruction may also carry addressing information.

1.8 8086 internal organization: BIU + EU

Bus Interface Unit (BIU)Execution Unit (EU)
Segment registers CS, DS, SS, ESGeneral registers AX, BX, CX, DX
Instruction Pointer IPPointer/index registers SP, BP, SI, DI
6-byte instruction queueALU
Physical address generation (segment + offset)FLAGS register
Memory and I/O bus operationsInstruction decoder and control
Fetches instructions using CS:IPExecutes decoded instructions
Performs memory reads/writes requested by the EUTakes bytes from the queue, decodes, executes
Performs I/O transfers for IN/OUTALU does arithmetic, logic, shifts, comparisons
Maintains and refills the queueReads/updates general registers and FLAGS; asks the BIU for memory/I/O

1.9 Prefetch queue (pipelining)

  • The BIU fetches instructions while the EU executes (overlap).
  • The queue holds up to 6 instruction bytes.
  • When the bus is free, the BIU fills empty queue positions.
  • The EU reads instruction bytes from the queue.
  • A taken jump, CALL, RET, or interrupt changes the execution address, so the processor discards the invalid prefetched bytes and refills the queue.

2. Registers and what they are used for

All registers are 16 bits wide. There are 4 groups:

2.1 General registers (each splits into 8-bit halves)

RegNameTypical use8-bit halves
AXAccumulatorArithmetic, I/O, MUL/DIV, DOS function number (AH)AH (high), AL (low)
BXBaseBase address for memory ([BX])BH, BL
CXCountLoop counter (LOOP)CH, CL
DXDataHigh word of MUL/DIV (DX:AX), I/O port, DOS string addressDH, DL

Writing AL changes only the low byte of AX (AH is unchanged).

2.2 Pointer and index registers

RegNameUse
SPStack PointerTop of the stack within SS
BPBase PointerAccesses parameters and local data in the stack segment
SISource IndexPoints to source data (string ops use DS:SI)
DIDestination IndexPoints to destination data (string ops use ES:DI)

2.3 Segment registers (select active memory segments)

RegSegmentUsed with
CSCode segmentIP for instruction fetch
DSData segmentDefault for most variables
SSStack segmentSP or BP
ESExtra segmentDestination for string operations (DI)

A segment register supplies the upper part of the 20-bit physical address.

2.4 Instruction Pointer and FLAGS

  • IP = offset of the next instruction within the code segment, so CS:IP = next instruction address.
  • IP is changed through jumps, calls, returns, interrupts, never by MOV IP, value.
  • FLAGS = status flags (results of arithmetic/logic) + control flags (affect processor operation).

3. Flags

3.1 Status flags

FlagNameSet (=1) when…
CFCarryCarry out of the MSB (addition) or borrow (subtraction), unsigned overflow
PFParityLow byte of the result has an even number of 1s
AFAuxiliary carryCarry/borrow between bit 3 and bit 4 (used for BCD)
ZFZeroResult = 0
SFSignMSB of the result is 1 (negative in signed)
OFOverflowSigned result does not fit (e.g. pos + pos = neg)

3.2 Control flags

FlagNameEffect
TFTrapSingle-step execution (debugging)
IFInterrupt enableEnables maskable interrupts
DFDirectionString direction (0 = increment SI/DI, 1 = decrement)

Not every instruction changes every flag. Check the instruction definition. MOV changes no flags; INC/DEC do not change CF; LOOP changes no arithmetic flags.

3.3 Worked example: FFh + 01h (8-bit)

mov al, 0FFh
add al, 01h
  11111111
+ 00000001
----------
1 00000000   (carry out)
  • AL = 00h
  • ZF = 1: the result is zero
  • CF = 1: carry out of bit 7
  • SF = 0: MSB is 0
  • OF = 0: signed −1 + 1 = 0 is representable
  • (also: PF = 1, since 00h has zero 1-bits = even; AF = 1, since F + 1 carries from bit 3 to bit 4)

4. Memory addressing

4.1 Segment:offset → physical address

Physical address = segment × 16 + offset (equivalently: shift the segment left 4 bits, i.e. append a hex 0, then add the offset)

  • Segment:offset = logical address
  • The 20-bit result = physical address placed on the bus
  • Many logical addresses can refer to the same physical byte.

Example: DS = 1200h, offset = 0340h

1200h × 10h = 12000h
            + 00340h
            --------
              12340h

Logical DS:0340h, physical 12340h (fits in 20 bits).

4.2 Default segment selection

AccessDefault
InstructionCS:IP
Stack via SPSS:SP
Memory via BPSS:BP
Source stringDS:SI
Destination stringES:DI
Most other memory operandsDS
  • A segment override prefix can select another segment.
  • The assembler determines the default from the addressing form.

4.3 Little-endian storage

The least significant byte is at the lower address. If AX = 1234h is stored at 2000h: M[2000h] = 34h, M[2001h] = 12h. The register still reads 1234h. Endianness concerns byte order in memory, not how hex digits are written in a register.

4.4 Effective-address (EA) forms

ModeExamples
Direct[value]
Register indirect[BX], [BP], [SI], [DI]
Based / indexed (+ displacement)[BX+4], [BP+6], [SI+2]
Based-indexed[BX+SI], [BP+DI]
Based-indexed + displacement[BX+DI+8]
  • Base = BX or BP; index = SI or DI. Only valid 8086 combinations are allowed.
  • AX, CX, DX, SP cannot form a memory effective address.
  • If BP is used, the default segment is SS; otherwise DS.

EA example: BX = 1000h, SI = 0020h, disp = 0004h

mov ax, [bx + si + 4]   ; EA = 1000h + 0020h + 0004h = 1024h → DS:1024h, reads a 16-bit word

BX+SI is a valid pair; no BP, so DS is the default. The physical address still needs the value of DS.


5. Assembly operations

5.1 Operand categories

TypeExample
ImmediateMOV AX, 5
RegisterMOV AX, BX
MemoryMOV AX, [value]
I/O portIN AL, 60h

Restrictions:

  • MOV memory, memory is invalid.
  • Operand sizes must agree.
  • CS cannot receive an immediate with MOV (segment registers cannot take an immediate directly).
  • Most instructions allow at most one explicit memory operand.
InvalidCorrect
mov [x], [y]mov ax, [y] then mov [x], ax
add [x], [y]mov ax, [y] then add [x], ax
mov ds, 1200hmov ax, 1200h then mov ds, ax
mov ax, bl (size mismatch)mov al, bl

5.2 Data movement: MOV

Copies a value without changing the source. Does not affect flags.

mov ax, 25        ; immediate → register
mov bx, ax        ; register → register
mov [result], ax  ; register → memory
mov dx, [value]   ; memory → register
mov al, [byteVal] ; 8-bit memory load
mov word [Y], 6   ; size keyword needed when no register gives the size

The assembler needs enough info to know the operand size (use byte / word).

5.3 Arithmetic

InstructionMeaningFlags
add ax, bxAX = AX + BXUpdates arithmetic flags
sub ax, 5AX = AX − 5Updates arithmetic flags
inc cxCX = CX + 1CF unchanged
dec dxDX = DX − 1CF unchanged
neg axAX = 0 − AX (two’s complement)Updates flags
cmp ax, bxComputes AX − BX, discards the result, keeps the flagsUpdates flags
imul bxSigned: DX:AX = AX × BX (32-bit result)—
idiv word [J]Signed: DX:AX ÷ [J], AX = quotient, DX = remainder—

Operand widths must match.

5.4 Translating an expression: A = B + ((D − G) × (P + Q)) / J

mov ax, [D]
sub ax, [G]        ; AX = D - G
mov bx, ax         ; BX = D - G
mov ax, [P]
add ax, [Q]        ; AX = P + Q
imul bx            ; DX:AX = AX × BX
idiv word [J]      ; AX = quotient, DX = remainder
add ax, [B]        ; AX = B + quotient
mov [A], ax        ; store result

Assumptions: all variables are signed words, J ≠ 0, the quotient fits in AX. IMUL gives a 32-bit result in DX:AX; IDIV uses the full DX:AX dividend.

5.5 Comparison and conditional jumps

CMP prepares flags for a following conditional jump.

JumpConditionType
JE / JZZF = 1 (equal)any
JNE / JNZZF = 0 (not equal)any
JAabove (CF = 0 and ZF = 0)unsigned
JAEabove or equal (CF = 0)unsigned
JBbelow (CF = 1)unsigned
JGgreater (ZF = 0 and SF = OF)signed
JLless (SF ≠ OF)signed
JMPalways (unconditional)—

The same CMP can need different jumps depending on whether the data is signed or unsigned (above/below = unsigned, greater/less = signed).

5.6 If-else translation

High level:

X = P + Q
if X = 4 then Y = 6
else          Y = X + W

Steps: compute X → compare with 4 → branch to one case → prevent fall-through into the other.

    mov ax, [P]
    add ax, [Q]
    mov [X], ax          ; X = P + Q
    cmp ax, 4            ; flags from AX - 4 (AX unchanged)
    je  equal_four       ; ZF = 1 → then-block
    add ax, [W]          ; else: AX = X + W
    mov [Y], ax
    jmp finished         ; skip the then-block (no fall-through)
equal_four:
    mov word [Y], 6      ; 'word' sets the destination size
finished:

5.7 Count-controlled loop: LOOP

    mov cx, 5        ; iteration count
    mov ax, 0
repeat_add:
    add ax, 3
    loop repeat_add  ; CX = CX - 1; jump if CX ≠ 0
    ; AX = 15
  • LOOP decrements CX and jumps if CX ≠ 0.
  • LOOP does not change arithmetic flags.
  • If CX starts at 0, the 8086 does 65,536 iterations (0 − 1 = FFFFh).

6. The stack

  • SS = stack segment, SP = offset of the top.
  • The stack grows downward and holds 16-bit values (words).
  • PUSH: SP = SP − 2, then store the word at SS:SP.
  • POP: read the word at SS:SP, then SP = SP + 2.
  • CALL: pushes the return offset (address of the next instruction), then jumps to the procedure.
  • RET: pops the return offset into IP.
  • BP is used to reach parameters/local data on the stack (default segment SS).
  • Stack operations must be balanced (every PUSH has a matching POP), or RET returns to a wrong address.

Procedure call and return

start:
    mov ax, 7
    call double_ax     ; push return offset, jump to double_ax
    ; AX is now 14
    mov ax, 4C00h
    int 21h            ; terminate
double_ax:
    add ax, ax         ; AX = 2 × AX
    ret                ; pop return offset into IP

By convention the procedure returns its result in AX.


7. INT and DOS services

7.1 Interrupt mechanism

  • INT n: pushes FLAGS, CS, IP, then loads a new CS:IP from the Interrupt Vector Table.
  • IRET: restores IP, CS, and FLAGS (return from interrupt).

7.2 DOS INT 21h

DOS uses INT 21h for operating-system services; AH selects the function.

AHFunctionDetails
01hRead a characterCharacter returned in AL (echoed)
09hPrint a stringDX = string address, string ends with $
4ChTerminate programAL = return code (mov ax, 4C00h → code 0)

7.3 I/O instructions

  • IN AL, 60h reads from an I/O port; OUT writes to a port. The BIU performs these transfers.

8. NASM program structure and directives

8.1 Minimal .COM program

bits 16                  ; 16-bit instruction encoding
org 100h                 ; DOS .COM programs load at offset 0100h
start:                   ; label = an address
    mov dx, message      ; DX = address of the string
    mov ah, 09h          ; DOS: print string
    int 21h
    mov ax, 4C00h        ; DOS: terminate, return code 0
    int 21h
message db "Hello from 8086!$"   ; '$' ends the string for AH=09h
  • ; starts a comment.
  • INT 21h requests a DOS service.

8.2 Numbers, characters, constants

FormExample
Decimal25
Hexadecimal0FFh (leading 0 needed if it starts with A–F, otherwise it is read as a label)
Binary10110110b
Character"A"

EQU creates a symbolic constant and does not allocate memory:

BACKSPACE       equ 08h
CARRIAGE_RETURN equ 0Dh
DELETE          equ 7Fh
BUFFER_SIZE     equ 64

8.3 Data-definition directives

DirectiveSizeExample
dbbyte (8 bits)letter db "A"
dwword (16 bits)count dw 25 / values dw 10,20,30
dddouble word (32 bits)—
times n …Repeatbuffer times 64 db 0, words times 20 dw 0
  • In object-file projects, RESB / RESW reserve uninitialized storage in a BSS section.
  • In a flat .COM file, TIMES gives explicit bytes.

8.4 ORG

  • For DOS .COM, the program image starts at offset 0100h, hence ORG 100h.
  • ORG tells the assembler which offsets to assign to labels in a flat binary.
  • It does not fill memory, set DS at runtime, or move the program.
  • NASM does not need an END directive (unlike 68K-style assemblers).

9. Complete program: input buffer

Reads characters until Enter (carriage return), with backspace support.

bits 16
org 100h
start:
    mov si, buffer       ; SI → next free byte in the buffer
read_next:
    mov ah, 01h          ; DOS: read character → AL
    int 21h
    cmp al, 0Dh          ; carriage return (Enter)?
    je  exit_program     ; yes → finish
    cmp al, 08h          ; backspace?
    je  move_left
    mov [si], al         ; store character
    inc si               ; advance pointer
    jmp read_next
move_left:
    cmp si, buffer       ; buffer empty?
    je  read_next        ; yes → ignore backspace
    dec si               ; move pointer back one
    jmp read_next
exit_program:
    mov ax, 4C00h        ; terminate
    int 21h
buffer times 64 db 0     ; 64-byte buffer
  • Carriage return ends input.
  • Backspace moves the pointer back only if the buffer is not empty.
  • This version has no overflow check. Exercise: add it, for example before mov [si], al:
    cmp si, buffer + 64  ; buffer full?
    je  read_next        ; yes → ignore extra characters

10. Debugging by tracing state

  1. Before each instruction, record the relevant registers, flags, and memory.
  2. Execute one instruction.
  3. Update the destination and only the flags defined for that instruction.
  4. For memory operands: compute the effective offset, then the physical address when segments matter.
  5. For branches: justify the decision from specific flag values.

11. Exercises (with solutions)

Exercise A

  • DS = 2400h, BX = 0100h → physical address of [BX] = 2400h × 10h + 0100h = 24100h
  • Bytes 78h at 25000h and 56h at 25001h → word = 5678h (lower address = low byte)

Exercise B: if A < B (unsigned) then MAX = B else MAX = A

    mov ax, [A]
    cmp ax, [B]
    jae a_is_max        ; unsigned: A >= B → A is max
    mov ax, [B]         ; A < B → load B
    mov [MAX], ax
    jmp done
a_is_max:
    mov [MAX], ax       ; AX already holds A
done:

12. Quick checklist before the test

  • Stored-program model; fetch / decode / execute steps
  • BIU vs EU roles; 6-byte prefetch queue and when it is flushed
  • Address bus 20-bit (1 MB), data bus 16-bit
  • All 14 registers: AX BX CX DX, SP BP SI DI, CS DS SS ES, IP, FLAGS
  • Physical address = seg × 10h + offset; default segments
  • Little-endian
  • Valid EA combinations (BX/BP + SI/DI + disp)
  • 6 status flags + 3 control flags; which instructions affect which
  • MOV restrictions; IMUL/IDIV using DX:AX
  • Signed (JG/JL) vs unsigned (JA/JB) jumps
  • LOOP and CX (CX = 0 → 65,536 iterations)
  • PUSH/POP (SP ∓ 2), CALL/RET, INT/IRET
  • INT 21h: AH = 01h, 09h, 4Ch
  • Directives: bits, org, db/dw/dd, times, equ, resb/resw