1. The 8086 Programming Model

Definition – Programmer-visible registers

All named registers of the 8086 are 16 bits wide.

GroupRegistersTypical role
General purposeAX, BX, CX, DXAccumulator, base pointer, counter, data / I/O port
Pointer & indexSP, BP, SI, DIStack pointer, base pointer, source index, destination index
SegmentCS, DS, SS, ESCode, data, stack, extra segment
ControlIP, FLAGSInstruction pointer, status/control bits

Definition – 8-bit halves

AX, BX, CX, DX each expose two independent 8-bit halves:

  • AL = low byte (bits 0–7)
  • AH = high byte (bits 8–15)
AX (16 bits) AH AL bit 15 8 | 7 0

⚠️ SP, BP, SI, DI and the segment registers have no 8-bit halves.


2. The FLAGS Register

Definition – Status and control flags

FlagBitTypeSet to 1 when…
CF – Carry0StatusUnsigned result carried out / needed a borrow
PF – Parity2StatusLow byte of result has an even number of 1s
AF – Auxiliary carry4StatusCarry/borrow between bit 3 and bit 4 (BCD)
ZF – Zero6StatusResult is all zeros
SF – Sign7StatusMSB of the result is 1
OF – Overflow11StatusSigned result does not fit
TF – Trap8ControlSingle-step mode (debugging)
IF – Interrupt9ControlMaskable interrupts enabled
DF – Direction10ControlString operations move backward

The remaining bits are reserved and complete the 16-bit register.

Which flag answers which question

QuestionFlag
Did an unsigned operation go out of range?CF
Did a signed operation go out of range?OF
Is the result zero / were the operands equal?ZF
Is the result negative (as signed)?SF

3. A Basic Instruction Vocabulary

PurposeInstructions
Data transferMOV, PUSH, POP, XCHG
ArithmeticADD, ADC, SUB, SBB, INC, DEC
LogicAND, OR, XOR, NOT, TEST
Control flowJMP, Jcc, CALL, RET, LOOP
Shift & rotateSHL, SHR, SAR, ROL, ROR
Processor controlCLC, STC, CLD, STD, NOP

4. The MOV Instruction

Definition – MOV

MOV dest, src copies src into dest.

mov ax, 1234h        ; immediate → register
mov bx, ax           ; register → register
mov [result], ax     ; register → memory
mov al, [inputByte]  ; memory → register (byte)
mov ax, [wordValue]  ; memory → register (word)

Rules

  • The source is not altered.
  • Most forms do not change FLAGS.
  • Operand widths must match (byte↔byte, word↔word).
  • At most one memory operand.

⚠️ mov [A],[B] is illegal — memory-to-memory transfers must go through a register.

⚠️ An immediate cannot be moved directly into a segment register (mov ds,1200h is illegal) — see Exercise 2.


5. Operand Size

Definition – Byte vs word operations

SizeRegistersExampleBytes read
Byte (8 bits)AL AH BL BH CL CH DL DHmov al,[value]1
Word (16 bits)AX BX CX DX SP BP SI DImov ax,[value]2

Size specifiers

When no register fixes the size, the assembler cannot guess it:

mov byte [flag], 1    ; writes 1 byte
mov word [count], 1   ; writes 2 bytes

⚠️ mov [count],1 is ambiguous — NASM rejects it (“operation size not specified”).


6. Data Movement Trace

Worked example – Partial-register updates

mov ax, 1234h
mov al, 56h
mov bh, ah
AfterAHALAXBH
mov ax,1234h12h34h1234h?
mov al,56h12h56h1256h?
mov bh,ah12h56h1256h12h
  • Writing AL preserves AH.
  • Writing BH preserves BL.

⚠️ Always trace the exact destination width — writing a half never clears the other half.


7. Immediate Addressing

Definition – Immediate operand

The value is encoded inside the instruction itself.

mov ax, 25
add al, 5
cmp bx, 1000h
and dx, 0FFh
NotationMeaning
25Decimal (default)
1000hHexadecimal (h suffix)
0FFhHex starting with a letter → leading 0
00000001bBinary (b suffix)

⚠️ NASM uses no # prefix (unlike the 68K).
⚠️ FFh without the leading zero is read as a label name, not a number.


8. Direct Memory Addressing

Definition – Direct operand

A label names the memory location; brackets request its contents.

mov ax, [total]        ; AX ← contents of total
mov [result], ax       ; contents of result ← AX
add byte [counter], 1
SyntaxMeaning
[total]The value stored at total
totalThe address (offset) of total
  • The variable definition (db / dw) determines its storage size.
  • The default segment is usually DS.

Worked example

mov dx, message   ; DX ← offset of message (an address)
mov al, [message] ; AL ← first character of message

9. Register-Indirect Addressing

Definition – Register-indirect operand

A register holds the effective offset of the operand.

mov al, [bx]
mov ax, [si]
mov [di], al
mov ax, [bp+4]
RegisterDefault segment
BX, SI, DIDS
BPSS

⚠️ Only BX, BP, SI, DI can be used as address registers — [ax], [cx], [dx], [sp] are illegal on the 8086.


10. ADD and SUB

Definition

InstructionOperation
ADD d, s
SUB d, s

Both update CF, PF, AF, ZF, SF, OF.

Worked example – and

mov ax, [P]
add ax, [Q]
mov [R], ax
 
mov bx, [X]
sub bx, 10
mov [Y], bx

If and , then , ZF = 0, CF = 0.

⚠️ add [R],[P] is illegal — memory-to-memory arithmetic needs a register in between.


11. Carry and Signed Overflow

Definition – Two interpretations of the same bits

  • CF = 1 → carry/borrow outside the unsigned width.
  • OF = 1 → result is invalid as a signed number.

Overflow rule for addition: OF = 1 exactly when two operands of the same sign produce a result of the opposite sign.

Worked example – two 8-bit additions

OperationResultUnsigned viewSigned viewCFOFZFSF
FFh + 01h00h255 + 1 = 256 ✗−1 + 1 = 0 ✓1010
7Fh + 01h80h127 + 1 = 128 ✓127 + 1 = −128 ✗0101
flowchart LR
    A[Same bit pattern] --> U[Unsigned data?] --> C[Check CF]
    A --> S[Signed data?] --> O[Check OF]

⚠️ The intended data type decides which flag matters — the CPU always computes both.


12. ADC and SBB – Multiword Arithmetic

Definition

InstructionOperation
ADC d, s
SBB d, s

32-bit addition and subtraction (DX:AX op CX:BX)

; DX:AX = DX:AX + CX:BX
add ax, bx      ; low words, sets CF
adc dx, cx      ; high words + carry
 
; DX:AX = DX:AX - CX:BX
sub ax, bx      ; low words, sets CF (borrow)
sbb dx, cx      ; high words - borrow

Worked example –

StepOperationResultCF
1add ax,bx → FFFFh + 0001hAX = 0000h1
2adc dx,cx → 0001h + 0000h + 1DX = 0002h0

Result: ✓

flowchart LR
    L["ADD low words"] -- CF --> H["ADC high words"]

⚠️ Do not modify CF between the paired instructions (no ADD, SUB, CMP, shifts… in between).


13. INC, DEC, NEG, and CMP

Definitions

InstructionOperationFlag notes
INC dPreserves CF
DEC dPreserves CF
NEG d (two’s complement)CF = 1 unless operand was 0
CMP d, sComputes , discards resultSets flags like SUB

Worked examples

  • NEG AL with AL = 05h → AL = FBh (−5), CF = 1.
  • NEG AL with AL = 00h → AL = 00h, CF = 0.
  • CMP AL,7 with AL = 5 → computes 5 − 7: CF = 1 (borrow), ZF = 0, SF = 1; AL still 5.

💡 Because INC/DEC preserve CF, they can update a loop counter or pointer inside an ADC/SBB carry chain without breaking it.


14. Conditional Control

Definition – Compare-and-branch pattern

CMP sets the flags; a conditional jump (Jcc) tests them.

cmp ax, bx
je  equal_values     ; ZF = 1
ja  unsigned_above   ; unsigned AX > BX
jg  signed_greater   ; signed   AX > BX
equal_values:
mov byte [same], 1

Worked example – same bits, different decisions

AX = FFFFh, BX = 0001h:

InterpretationAXBXAX > BX?Jump taken
Unsigned655351YesJA ✓
Signed−11NoJG ✗

⚠️ Choose the jump by the meaning of the data, not by the bit pattern.


15. 8086 Conditional Jumps

Reference table

CategoryJumpMeaningCondition tested
EqualityJE / JZequal / zeroZF = 1
JNE / JNZnot equalZF = 0
UnsignedJAaboveCF = 0 and ZF = 0
JAE / JNCabove or equalCF = 0
JB / JCbelowCF = 1
JBEbelow or equalCF = 1 or ZF = 1
SignedJGgreaterZF = 0 and SF = OF
JGEgreater or equalSF = OF
JLlessSF ≠ OF
JLEless or equalZF = 1 or SF ≠ OF
OverflowJO / JNOoverflow / noneOF = 1 / 0
SignJS / JNSnegative / notSF = 1 / 0
ParityJP / JNPeven / odd parityPF = 1 / 0

💡 Memory aid: Above/Below = unsigned; Greater/Less = signed.


16. If–Else Translation

Worked example

High-level code:

    mov ax, [P]
    add ax, [Q]
    mov [X], ax
    cmp ax, 4
    je  equal_four
    add ax, [W]        ; false case
    mov [Y], ax
    jmp finished       ; skip the true case
equal_four:
    mov word [Y], 6    ; true case
finished:
flowchart TD
    A["AX ← P + Q; X ← AX"] --> B{"AX = 4 ?"}
    B -- "yes (JE)" --> T["Y ← 6"]
    B -- no --> F["Y ← AX + W"]
    F -- JMP --> E[finished]
    T --> E
  • CMP leaves AX unchanged.
  • JE enters the true case.
  • JMP prevents the false case from falling through into the true case.
  • word specifies the memory destination size.

⚠️ Forgetting the JMP finished makes the false branch also execute Y ← 6.


17. Logical Instructions

Definitions

InstructionEffectTypical use
AND d,sbitwise ANDClear selected bits (mask with 0)
OR d,sbitwise ORSet selected bits (mask with 1)
XOR d,sbitwise XORToggle selected bits; xor r,r zeros r
NOT dcomplement every bitOne’s complement
TEST d,sAND for flags onlyTest bits without changing d

Flag effects: AND, OR, XOR, TEST clear CF and OF (and set ZF, SF, PF from the result). NOT changes no flags.

Worked example – AL = 10110110b

InstructionMaskResult
and al,0Fh00001111b00000110b (upper nibble cleared)
or al,01h00000001b10110111b (bit 0 set)
xor al,80h10000000b00110110b (bit 7 toggled)
not al—01001001b
test al,04h00000100bAL unchanged, ZF = 0 (bit 2 is 1)

18. Input-Bit Masking

Worked example – combine bit 0 and bit 7

mov al, [input]
mov bl, al            ; keep a copy
and al, 00000001b     ; AL = input bit 0
and bl, 10000000b     ; BL = input bit 7 (still at position 7)
shr bl, 7             ; move it to position 0
or  al, bl            ; combine
mov [output], al

Trace with input = 10000110b:

StepALBL
after copies1000011010000110
and al,100000000—
and bl,80h—10000000
shr bl,7—00000001
or al,bl00000001—
flowchart LR
    I[input] --> A["AND 01h → bit 0"]
    I --> B["AND 80h → bit 7"] --> S["SHR 7 → bit 0"]
    A --> O["OR → output"]
    S --> O

💡 Copying into BL first preserves the original input value.


19. Shift Instructions

Definitions

InstructionDirectionBit insertedInterpretation
SHLleft0 at bit 0× 2 (if no significant bit lost)
SHRright0 at MSBunsigned ÷ 2
SARrightcopy of sign bit at MSBsigned ÷ 2

The last bit shifted out goes into CF.

Worked example – AL = 96h = 10010110b (unsigned 150, signed −106)

InstructionResultCFMeaning
shl al,100101100b = 2Ch1MSB lost → ×2 invalid in 8 bits
shr al,101001011b = 4Bh = 750150 / 2 = 75 ✓
sar al,111001011b = CBh = −530−106 / 2 = −53 ✓

⚠️ Rounding caveat: SAR rounds toward −∞. Example: −5 (FBh) sar 1 → FDh = −3, whereas signed division (IDIV) gives −2.


20. Count-Controlled Loop

Definition – LOOP

LOOP label: ; if , jump to label.

Worked example – sum 16 bytes

    mov cx, 16          ; iteration count
    mov si, buffer      ; pointer to first byte
    xor al, al          ; sum = 0
next_byte:
    add al, [si]
    inc si
    loop next_byte
flowchart TD
    I["CX ← 16, SI ← buffer, AL ← 0"] --> B["AL ← AL + [SI]; SI ← SI + 1"]
    B --> L["CX ← CX − 1"]
    L --> C{"CX ≠ 0 ?"}
    C -- yes --> B
    C -- no --> E[done]
  • LOOP does not alter arithmetic flags.

⚠️ Starting with CX = 0 decrements to FFFFh first → 65 536 iterations. Guard with jcxz if CX can be zero.
⚠️ The 8-bit sum in AL silently wraps past 255 — use a word accumulator for larger totals (see Lecture 5, Array traversal).


21. Assembler Source Structure

Definition – Instructions vs directives

ElementRoleExample
InstructionExecuted by the CPUmov ax,5
DirectiveGuides the assembler (no CPU code)bits 16, org 100h
LabelNames an addressstart:
CommentDocuments intent; init counter
DirectiveMeaning
bits 16Generate 16-bit code
org 100hCode starts at offset 100h (DOS .COM image)
dbDefine initialised byte(s)
dwDefine initialised word(s)
equDefine a symbolic constant (no storage)

22. Minimal Executable Program

Worked example – “Hello” in NASM / DOSBox-X

bits 16
org 100h
 
start:
    mov dx, message    ; DS:DX → string
    mov ah, 09h        ; DOS: print $-terminated string
    int 21h
    mov ax, 4C00h      ; DOS: terminate, return code 0
    int 21h
 
message db "Hello$"
sequenceDiagram
    participant P as Program
    participant D as DOS (INT 21h)
    P->>D: AH=09h, DX=message
    D-->>P: prints "Hello"
    P->>D: AH=4Ch, AL=00h
    D-->>P: process ends
  • INT is a processor instruction.
  • Function AH = 09h and the $ terminator belong to the DOS service, not the CPU.
  • AH = 4Ch terminates the process (AL = return code).

⚠️ Without the $, function 09h keeps printing memory until it happens to find one.


23. Debugging Workflow

  1. Assemble and read every diagnostic.
  2. Set a breakpoint before the faulty region.
  3. Record registers and flags.
  4. Single-step one instruction at a time.
  5. Verify memory addresses and operand widths.
  6. Distinguish a CPU instruction from a DOS service.
  7. Test both sides of every branch.
  8. Check loop entry and termination conditions.

⚠️ Trace before changing the program — guessing fixes often hide the real bug.


24. Exercises

Exercise 1 – Registers and flags

Execute ADD AL,01h with AL = FFh, then with AL = 7Fh. Find AL, CF, ZF, SF, OF.

Start ALResult ALCFZFSFOF
FFh00h1100
7Fh80h0011

Why they differ: FFh + 01h overflows the unsigned range (255 + 1) but is a valid signed sum (−1 + 1 = 0). 7Fh + 01h is a valid unsigned sum (128) but overflows the signed range (127 + 1 ≠ −128).

Exercise 2 – Repair the invalid instructions

InvalidProblemRepair
mov [A],[B]Two memory operandsmov ax,[B] / mov [A],ax
add ax,blWidth mismatch (16 vs 8)xor bx,bx / mov bl,[small] / add ax,bx
mov ds,1200hImmediate → segment registermov ax,1200h / mov ds,ax
mov [count],1Size unspecifiedmov word [count],1
  • A register bridges memory operands.
  • Mixed widths require deliberate zero extension.
  • A segment register is loaded through a general register.
  • The memory write states its size explicitly.