0. Tools: NASM vs MASM vs EMU8086
| Criterion | NASM | MASM | EMU8086 |
|---|---|---|---|
| Full name | Netwide Assembler | Microsoft Macro Assembler | 8086 Microprocessor Emulator |
| Main purpose | Assemble x86 source | Assemble Microsoft-style x86 source | Teach & simulate 8086 programs |
| CPU simulation | No | No | Yes |
| Visual debugger | No | Through external Microsoft tools | Yes |
| Register/flag display | Needs a debugger/emulator | Needs a debugger | Built in |
| 8086 support | Excellent | Historically excellent | Designed specifically for 8086 |
| macOS | Excellent | Poor | No native version |
| Windows | Excellent | Excellent | Yes |
| Linux | Excellent | No native support | No native support |
| License | Free, open source | Included with Microsoft tools | Proprietary trial/commercial |
| Syntax | Clear, relatively simple | Powerful but directive-heavy | MASM-like + proprietary extensions |
| Best use | Course standard, portable projects | Windows/Microsoft development | Beginner demos |
| Peripheral simulation | No | No | Limited simulated devices |
| Proteus integration | Possible (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], ax1.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
| Bus | Role | 8086 width |
|---|---|---|
| Address bus | CPU places the address of the required memory location | 20 bits, so 2²⁰ = 1,048,576 bytes (1 MB) addressable |
| Data bus | Carries instruction or data values | 16 bits (external) |
| Control signals | Indicate memory read, memory write, or I/O operation | — |
1.4 Instruction cycle
Fetch (gets the next instruction):
- Form the address from CS and IP (CS:IP).
- The Bus Interface Unit (BIU) reads instruction bytes from memory.
- The bytes enter the 6-byte prefetch queue.
- The Execution Unit (EU) takes instruction bytes from the queue.
- 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 model | Meaning | 8086 equivalent |
|---|---|---|
| MAR (Memory Address Register) | Holds a memory address | Conceptual, not accessible to programs |
| MBR / MDR (Memory Buffer/Data Register) | Holds the transferred data | Conceptual, not accessible |
| IR (Instruction Register) | Holds the current instruction | Internal |
| PC (Program Counter) | Identifies the next instruction | IP (combined with CS) |
| ALU | Operates on temporary data | ALU in the EU |
| — | Status/control info | FLAGS |
1.6 Register Transfer Language (RTL)
A compact notation to describe internal operations. It describes meaning, not assembler syntax.
[AX]= contents of AXM[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, ES | General registers AX, BX, CX, DX |
| Instruction Pointer IP | Pointer/index registers SP, BP, SI, DI |
| 6-byte instruction queue | ALU |
| Physical address generation (segment + offset) | FLAGS register |
| Memory and I/O bus operations | Instruction decoder and control |
| Fetches instructions using CS:IP | Executes decoded instructions |
| Performs memory reads/writes requested by the EU | Takes bytes from the queue, decodes, executes |
| Performs I/O transfers for IN/OUT | ALU does arithmetic, logic, shifts, comparisons |
| Maintains and refills the queue | Reads/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)
| Reg | Name | Typical use | 8-bit halves |
|---|---|---|---|
| AX | Accumulator | Arithmetic, I/O, MUL/DIV, DOS function number (AH) | AH (high), AL (low) |
| BX | Base | Base address for memory ([BX]) | BH, BL |
| CX | Count | Loop counter (LOOP) | CH, CL |
| DX | Data | High word of MUL/DIV (DX:AX), I/O port, DOS string address | DH, DL |
Writing AL changes only the low byte of AX (AH is unchanged).
2.2 Pointer and index registers
| Reg | Name | Use |
|---|---|---|
| SP | Stack Pointer | Top of the stack within SS |
| BP | Base Pointer | Accesses parameters and local data in the stack segment |
| SI | Source Index | Points to source data (string ops use DS:SI) |
| DI | Destination Index | Points to destination data (string ops use ES:DI) |
2.3 Segment registers (select active memory segments)
| Reg | Segment | Used with |
|---|---|---|
| CS | Code segment | IP for instruction fetch |
| DS | Data segment | Default for most variables |
| SS | Stack segment | SP or BP |
| ES | Extra segment | Destination 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
| Flag | Name | Set (=1) when… |
|---|---|---|
| CF | Carry | Carry out of the MSB (addition) or borrow (subtraction), unsigned overflow |
| PF | Parity | Low byte of the result has an even number of 1s |
| AF | Auxiliary carry | Carry/borrow between bit 3 and bit 4 (used for BCD) |
| ZF | Zero | Result = 0 |
| SF | Sign | MSB of the result is 1 (negative in signed) |
| OF | Overflow | Signed result does not fit (e.g. pos + pos = neg) |
3.2 Control flags
| Flag | Name | Effect |
|---|---|---|
| TF | Trap | Single-step execution (debugging) |
| IF | Interrupt enable | Enables maskable interrupts |
| DF | Direction | String direction (0 = increment SI/DI, 1 = decrement) |
Not every instruction changes every flag. Check the instruction definition.
MOVchanges no flags;INC/DECdo not change CF;LOOPchanges 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
| Access | Default |
|---|---|
| Instruction | CS:IP |
| Stack via SP | SS:SP |
| Memory via BP | SS:BP |
| Source string | DS:SI |
| Destination string | ES:DI |
| Most other memory operands | DS |
- 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
| Mode | Examples |
|---|---|
| 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 wordBX+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
| Type | Example |
|---|---|
| Immediate | MOV AX, 5 |
| Register | MOV AX, BX |
| Memory | MOV AX, [value] |
| I/O port | IN AL, 60h |
Restrictions:
MOV memory, memoryis 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.
| Invalid | Correct |
|---|---|
mov [x], [y] | mov ax, [y] then mov [x], ax |
add [x], [y] | mov ax, [y] then add [x], ax |
mov ds, 1200h | mov 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 sizeThe assembler needs enough info to know the operand size (use byte / word).
5.3 Arithmetic
| Instruction | Meaning | Flags |
|---|---|---|
add ax, bx | AX = AX + BX | Updates arithmetic flags |
sub ax, 5 | AX = AX − 5 | Updates arithmetic flags |
inc cx | CX = CX + 1 | CF unchanged |
dec dx | DX = DX − 1 | CF unchanged |
neg ax | AX = 0 − AX (two’s complement) | Updates flags |
cmp ax, bx | Computes AX − BX, discards the result, keeps the flags | Updates flags |
imul bx | Signed: 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 resultAssumptions: 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.
| Jump | Condition | Type |
|---|---|---|
JE / JZ | ZF = 1 (equal) | any |
JNE / JNZ | ZF = 0 (not equal) | any |
JA | above (CF = 0 and ZF = 0) | unsigned |
JAE | above or equal (CF = 0) | unsigned |
JB | below (CF = 1) | unsigned |
JG | greater (ZF = 0 and SF = OF) | signed |
JL | less (SF ≠ OF) | signed |
JMP | always (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 IPBy 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.
| AH | Function | Details |
|---|---|---|
| 01h | Read a character | Character returned in AL (echoed) |
| 09h | Print a string | DX = string address, string ends with $ |
| 4Ch | Terminate program | AL = return code (mov ax, 4C00h → code 0) |
7.3 I/O instructions
IN AL, 60hreads from an I/O port;OUTwrites 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
| Form | Example |
|---|---|
| Decimal | 25 |
| Hexadecimal | 0FFh (leading 0 needed if it starts with A–F, otherwise it is read as a label) |
| Binary | 10110110b |
| 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 648.3 Data-definition directives
| Directive | Size | Example |
|---|---|---|
db | byte (8 bits) | letter db "A" |
dw | word (16 bits) | count dw 25 / values dw 10,20,30 |
dd | double word (32 bits) | — |
times n … | Repeat | buffer 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
ENDdirective (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 characters10. Debugging by tracing state
- Before each instruction, record the relevant registers, flags, and memory.
- Execute one instruction.
- Update the destination and only the flags defined for that instruction.
- For memory operands: compute the effective offset, then the physical address when segments matter.
- 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