Microprocessors · Lecture Notes

Chapter 3.2: Assembly Language

Assembly language writes a processor's machine instructions as human-readable abbreviations. Every instruction line corresponds to a single machine instruction. For that reason, anyone writing assembly manages registers, memory, and flags directly; every detail a compiler would hide becomes visible. These notes treat 8086 assembly in the emu8086 environment. First come the fields of a line, the difference between an instruction and a directive, and the naming rules. Then we examine operand types, the implicit operands that instructions do not spell out, and the cost of a memory access in clock periods. We trace step by step how IP advances on every instruction and which instructions change the flags. The last sections write a first .COM program, read the bytes it occupies in memory one by one, run it in the emu8086 window, and classify the most common mistakes together with their causes.

Learning outcomes

Explain where assembly fits
Show the one-to-one relationship between assembly language and machine language, and how it differs from high-level languages, through the three views of a single instruction.
Read the structure of a line
Separate the label, instruction, operand, and comment fields; tell an instruction from a directive and a macro; recognize valid and invalid names.
Recognize operands
Identify register, immediate, and memory operands, and the implicit operands of instructions such as MUL, DIV, LOOP, CBW, PUSH, and XLAT.
Compute instruction timing
Find the time difference between instructions with register and memory operands using clock periods and effective address calculation; explain the difference through bus cycles.
Trace IP and the flags
Trace step by step how IP advances by the instruction length and what instructions that change or leave the flags alone do.
Write the first program
Write a .COM program in emu8086, read its bytes, run it one step at a time; tell a syntax error from a logic error.

3.2.1Assembly language

3.2.1.1Mnemonics and the machine instruction

A microprocessor decodes the bytes it reads from memory and turns each byte sequence into an operation. The language made of these bytes is called machine language. Machine language is the only language the processor understands directly, but it is hard for people to read. Someone looking at the bytes B8 05 00 can work out that they mean “load 5 into register AX” only by consulting a table. When a program reaches hundreds of instructions, this method breaks down.

Assembly language was born to solve this problem. Every machine instruction is given a short, memorable name: MOV for moving, ADD for addition, JMP for jumping. These short names are called mnemonics. Operands are also written by name instead of by number: registers as AX and BX, and memory locations by names the programmer chooses.

Definition 3.2.1

Assembly language is a low-level programming language that writes a processor's machine instructions with mnemonics and symbolic names. Each instruction line in assembly source corresponds to a single machine instruction of the processor. This one-to-one relationship makes the language processor-dependent: every processor family has its own assembly language.

The easiest way to see the one-to-one relationship is to write a single line in three different forms. Table 3.2.1 shows the line MOV AX, 5 side by side as the programmer, the assembler, and the processor see it.

Table 3.2.1: One line, three views.
ViewNotationWho uses it?
AssemblyMOV AX, 5programmer
Hexadecimal machine codeB8 05 00listing, emulator, debugger
Binary machine code10111000 00000101 00000000processor (voltage levels on the data bus)

The first byte B8 is the opcode of the operation “load an immediate value into a 16-bit register.” In this instruction family the number of the destination register is added to the opcode. Since AX is number 0, the code is B8h + 0 = B8h. BX is number 3; that is why the first byte of MOV BX, 3 is BBh. The remaining two bytes of the instruction carry the 16-bit constant. The value 0005h is stored in memory low byte first: 05 first, then 00. This byte order of the 8086 is called little-endian.

The binary line is what the processor actually sees. The 8086 reads instruction bytes over the address/data lines (AD0–AD15). Each bit is a high or low voltage on one line. Seen through the eyes of an electronic circuit, MOV AX, 5 is nothing but a 24-bit pattern arriving at the input of the instruction decoder. The decoder turns this pattern into control signals that drive the ALU, the write input of the register file, and the internal buses.

This closeness is also what separates assembly from high-level languages. A programmer who writes x = a * b; in C does not know in which register the multiplication will be done; the compiler chooses. In assembly, it is the programmer's responsibility that the multiplicand sits in AL, that the result is written to AX, and that the old value in AH is wiped out. The power of the language and its difficulty both come from here. Writing assembly requires knowing the registers, the memory, and the system bus. In return, how a program runs in hardware can be seen in every detail.

Example 3.2.1

What is the machine code of MOV BX, 1234h? How many bytes does it occupy in memory?

The instruction family is the same: an immediate value into a 16-bit register. The opcode is B8h + the register number. Since BX is number 3, the first byte is BBh. The constant 1234h is written low byte first: 34h, then 12h. The instruction is BB 34 12 and occupies three bytes. There is a separate family for 8-bit registers: MOV AL, 5 is encoded in two bytes as B0 05, because the constant is a single byte.

3.2.1.2The assembler and emu8086

Assembly source is a plain text file. The processor cannot run this text; it must first be translated into machine code. The program that does this translation is called an assembler. The assembler translates mnemonics into opcodes, labels into addresses, and variable names into relative locations. The translation is one-to-one: one instruction line yields one machine instruction. MASM, TASM, and NASM are common assemblers for the 8086 family.

The translated code is written to a file. For simple programs this file is directly a runnable .COM file. Multi-segment programs are first translated into an object file (.obj); then the linker combines the object files and produces an .EXE file. To run the program, the operating system's loader copies the file into RAM, sets the segment registers, and hands control to the program's first instruction. Figure 3.2.1 shows this chain.

source.asmtextAssemblertranslates one-to-oneobject / .COMmachine codeLoaderloads into RAMfor EXE the linker comes in between: .obj → .exe
Figure 3.2.1: From source file to memory. The assembler translates the text one-to-one into machine code, and the loader places the result in RAM. For .EXE files the linker comes in between.

emu8086, used in this course, gathers all the links of the chain in a single window. It contains a text editor, an assembler, and an 8086 emulator. An emulator is a program that imitates the 8086 in software. In a real processor the insides of the registers are not visible from outside; the emulator, by contrast, shows the registers, memory, and flags on the screen after every instruction. A program can be advanced one instruction at a time, stepped back, and stopped wherever you like. While learning assembly this is the most valuable tool, because the effect of every instruction can be predicted and tested immediately.

The difference between the .COM and .EXE formats also determines the structure of the program. Table 3.2.2 compares the two formats.

Table 3.2.2: .COM and .EXE programs.
Feature.COM.EXE
Number of segmentsa single segment; code, data, and stack within the same 64 KBmultiple segments (separate code, data, and stack)
Size limit64 KB minus 256 bytes (PSP) and room for the stackthe 64 KB limit applies to each segment separately
File headernone; the file is copied into memory as it ispresent; contains a relocation table and initial values
Start addressORG 100h, IP = 0100hthe label given in the END directive
Segment registersCS = DS = ES = SSthe program loads DS itself

All the examples in these notes are in the .COM format and are written in emu8086 syntax. Most of the examples also assemble unchanged with MASM and TASM. The byte values of the instructions and the IP and register traces were obtained by running them on an 8086 emulator.

3.2.1.3When is assembly used?

A program written in assembly is generally smaller and faster than a high-level program that does the same job. The reason is simple: the program contains only the instructions the programmer wrote. There is no startup code added by a compiler, no library calls, and no general-purpose helper routines. Why every instruction is there is known.

A more important advantage than speed is direct access to the hardware. Some 8086 instructions have no counterpart in standard C. OUT writes a byte to an I/O port, CLI disables interrupts, and PUSHF pushes the flags register onto the stack. Bootloaders, device drivers, interrupt service routines, and small embedded systems are therefore written wholly or partly in assembly. The first code that runs when a computer is powered on is assembly anyway, since the stack and memory layout have not yet been set up.

The price of the language is also heavy. Table 3.2.3 summarizes both sides.

Table 3.2.3: Pros and cons of programming in assembly.
ProsCons
Takes less space; there is no unnecessary code.Not portable: 8086 code does not run on an ARM processor.
Fast, because it performs only the necessary operations.Laborious to write, read, and debug.
Gives port I/O, interrupt handling, and direct access to the flags.Low productivity in large projects.
Indispensable in bootloaders, drivers, and embedded systems.Modern compilers often produce code that is fast enough.

In practice the two sides are used together. Most of the program is written in a language such as C. Small time-critical pieces, such as the entry of an interrupt routine or the inside of a frequently called loop, are written in assembly. This mixed approach preserves both development speed and run speed. Another benefit of knowing assembly is reading high-level code. An engineer who can look at the assembly output a compiler produced can find out why the code runs slowly or why a variable took an unexpected value.

Common mistake

Believing “assembly is always faster.” Hand-written assembly is fast only if the programmer knows the processor better than the compiler does. A loop counter kept in memory, memory reads repeated needlessly, or a badly chosen instruction yield a program slower than the code a good compiler would produce. Speed comes less from the language than from choosing register and memory use correctly.

3.2.2The structure of an instruction line

3.2.2.1The fields of a line

Assembly source is read line by line. Each line carries at most one instruction or one directive. The general form of an instruction line is as follows; the fields in square brackets are optional:

[label:]  instruction  [destination], [source]  [; comment]

Figure 3.2.2 shows these fields on the line start: MOV AX, 5 ; AX ← 5. The label is the name given to the address of the line. The instruction field carries the mnemonic. After the instruction come at most two operands separated by a comma. The part from the semicolon to the end of the line is the comment.

start:labelMOVinstructionAXdestination,5source; AX ← 5comment→ AX ← 5
Figure 3.2.2: The fields of an instruction line. The label start, the instruction MOV, AX the destination operand, 5 the source operand, and everything after the semicolon is a comment. The effect of the line is the assignment AX ← 5.
Definition 3.2.2

An operand is the value, register, or memory location an instruction operates on. In two-operand instructions in Intel syntax, the left operand is the destination and the right one is the source. The instruction reads the source and writes the result to the destination. The source does not change; the old value of the destination is lost.

The destination–source order is where everyone learning assembly first stumbles. MOV AX, BX is read not as “move AX to BX” but as “AX ← BX.” This order is the same as assignment in C: ax = bx;. Two-operand arithmetic instructions follow the same rule. When SUB CX, AX runs, CX ← CX − AX; AX does not change. Thus the destination operand is both the first input and the place where the result is written.

Not every instruction takes two operands. Table 3.2.4 splits three lines with different numbers of operands into their fields.

Table 3.2.4: The fields of three lines.
LineLabelInstructionOperandsComment
start: MOV AX, 5 ; AX ← 5startMOVAX, 5; AX ← 5
INC AX—INCAX—
RET—RETnone—

INC AX has one operand: AX is both source and destination, and AX ← AX + 1. RET writes no operand at all, but it still does work: it reads a word from the stack and puts it into IP. These unwritten operands are treated in detail under implicit operands.

The assembler is case-insensitive. mov ax, bx, MOV AX, BX, and Mov Ax, Bx give the same machine code. The number of spaces and tabs is also unimportant; aligning the fields one under another is only for readability. Comments never enter the machine code. When the assembler sees a semicolon, it skips the rest of the line. A comment can therefore be as long as you like without affecting the size or speed of the program.

Comments matter more in assembly than in high-level languages. The line ADD AX, BX already says what it does; it does not say why. Whether AX holds a running total, an address, or a counter cannot be told from the code. A good comment does not repeat the instruction as “AX ← AX + BX”; it states the purpose, such as “add this student's grade to the total.”

3.2.2.2Instruction, directive, and macro

Not every line in an assembly source produces machine code. Lines fall into three kinds.

Definition 3.2.3

An instruction is an operation the processor executes at run time and is translated into a single machine instruction. A directive is information given to the assembler: it states where the code will be placed, how much space to reserve, and what a name will stand for. A directive produces no machine instruction; data-definition directives produce only data bytes. A macro is a named text pattern that is replaced by several lines at assembly time.

The difference between an instruction and a directive is in timing. The instruction is executed by the processor while the program runs. A directive carries meaning only at assembly time; when the program starts to run, no trace of it remains. Table 3.2.5 gives frequently used lines with their kinds and what they produce in memory.

Table 3.2.5: Line kinds and what they produce in memory.
LineKindWhat does it produce in memory?
MOV AX, 5instructionmachine code: B8 05 00
ORG 100hdirectivenothing; sets the location counter to 0100h
num DB 0directive (data definition)1 byte of data: 00
k EQU 5directivenothing; the name k takes the value 5
ENDdirectivenothing; the source ends here
PUTC 'A'macro callthe code of the instructions in the macro body

To understand how directives work, one must know the assembler's location counter. While reading the source from top to bottom, the assembler keeps in a counter the relative location where the next byte will be placed. Each instruction or data definition advances the counter by the number of bytes it produces. ORG 100h sets the counter directly to 0100h; it produces no bytes itself. EQU, on the other hand, never touches the counter: it only binds a name to a constant. The assembler writes 5 wherever it sees the name k. The line num DB 0 binds the current value of the counter to the name num, reserves one byte, and puts 0 into it.

The small program below makes this difference concrete. The comments on the right show the addresses and bytes in the assembler's listing.

ORG 100h            ; no bytes; location counter = 0100h
k EQU 5             ; no bytes; k = 5
MOV AX, 5           ; 0100h: B8 05 00
MOV BX, k           ; 0103h: BB 05 00  (5 in place of k)
MOV AL, num         ; 0106h: A0 0A 01  (num = 010Ah)
RET                 ; 0109h: C3
num DB 0            ; 010Ah: 00
END                 ; no bytes

Of the eight lines only five produce bytes, and the program is 11 bytes. The codes of MOV AX, 5 and MOV BX, k are the same apart from the register number, because the assembler put 5 in place of k. A constant defined with EQU occupies no memory. The situation is different in the line MOV AL, num. num is a memory location; the instruction reads the byte at that location. The assembler writes the location's address into the instruction: 010Ah, low byte first, 0A 01. This address is not known until the assembler reaches the num line. How the assembler resolves this forward reference is explained by two-pass assembly; what matters here is that the address is computed at assembly time and embedded in the instruction.

The macro is the third kind. PUTC 'A', from the emu8086.inc library that ships with emu8086, is the name of a pattern of a few instructions that prints one character on the screen. When the assembler sees this line, it copies the body of the macro in place of the line and translates the copy. A macro call is not a subroutine call: the body is rewritten at every use and the program grows accordingly. Macros are a separate topic; they are mentioned here only to show that one line can produce more than one machine instruction.

Common mistake

Treating an EQU constant as a variable. After the definition k EQU 5, writing MOV k, 7 means “5 ← 7” and the assembler reports an error. An EQU name occupies no memory; its value is fixed at assembly time and cannot be changed at run time. A quantity whose value will change is defined with DB or DW.

3.2.2.3Labels and names

In an assembly program, addresses are written as names instead of numbers. The name given to the address of an instruction is called a code label, and the name given to a data area is called a variable name. Both are bound to an address in the assembler's symbol table, but they are used differently.

start:  MOV CX, 3   ; code label
again:  INC AX
        LOOP again  ; again = address
        RET
num     DB 7        ; data name

A code label ends with a colon. The label itself produces no machine code; it only stands for the address of the instruction that follows it, that is, its relative location within CS. If this program is assumed to start with ORG 100h, start = 0100h. MOV CX, 3 is three bytes (B9 03 00); again = 0103h. INC AX is a single byte (40), and LOOP again is two bytes (E2 FD). RET is at 0106h and num at 0107h.

The second byte of LOOP again, FDh, is noteworthy. The instruction stores not the address but the displacement. When LOOP executes, IP already points to the next instruction, that is, 0106h. Since the target is 0103h, the displacement is 0103h − 0106h = −3. −3 is written as FDh in 8-bit two's complement. The label spares the programmer this calculation: the programmer writes again and the assembler computes the displacement. When a new instruction is added to the program and addresses shift, the calculation is renewed automatically.

A variable name is written without a colon. For a variable name, the assembler keeps three pieces of information: its address, its segment, and its type. A name defined with DB has type byte, and one defined with DW has type word. The type information lets the assembler check sizes. If MOV AX, num is written after the definition num DB 7, the assembler notices that an 8-bit variable is being moved into a 16-bit register and reports an error.

The rules for names are as follows:

  • A name begins with a letter or an underscore; it cannot begin with a digit. Any string that begins with a digit is a number to the assembler.
  • The rest of the name may contain letters, digits, and underscores.
  • Instruction, register, and directive names (MOV, AX, DB, END …) cannot be used as names; these are reserved words.
  • Case is not distinguished. again and AGAIN are the same label; defining both gives a “defined twice” error.
Table 3.2.6: Examples of names.
NameValid?Why?
_countyesbegins with an underscore
total2yesbegins with a letter, the digit comes later
2totalnobegins with a digit; the assembler takes it for an invalid number
cxnoit is a register name (same as CX)
last-valueno− is an operator; the assembler reads last minus value

The last row is instructive. last-value is parsed as an expression. If the names last and value do not exist in the program, the assembler reports an “undefined symbol” error; if they do, it computes the difference of the two addresses and produces a number the programmer never wanted. Underscores are therefore used in names made of several words: last_value.

Common mistake

Thinking Num and num are two different variables. C and Java distinguish case; 8086 assemblers do not. A programmer who writes MOV Num, 3 after the definition num DB 7 may think a new variable has been created, but the instruction writes 3 to the same byte and the 7 is lost. The assembler does not count this as an error, because the line is valid. Different quantities are given different names.

3.2.3Operands

3.2.3.1Register, immediate value, and memory

The operand of an instruction can come from three places: a register inside the processor, the instruction's own bytes, or memory. These three kinds behave differently both in syntax and in hardware.

Table 3.2.7: Three operand types.
TypeExampleWhere does the value come from?Restriction
RegisterMOV AX, BXfrom the register file inside the processorthe fastest type
Immediate valueMOV AX, 5from within the bytes of the instructioncan only be a source
MemoryMOV AX, [BX]from memory, with a bus cycleat most one per instruction

A register operand is inside the processor. The 8086's execution unit (EU) has eight general-purpose 16-bit registers: AX, BX, CX, DX, SP, BP, SI, and DI. The first four can also be used through their 8-bit halves: AH and AL, BH and BL, CH and CL, DH and DL. An instruction with register operands never goes out onto the external bus. The value travels over the internal bus to the ALU, and the result returns to the register over the internal bus.

An immediate value is a constant embedded in the instruction. The bytes 05 00 of MOV AX, 5 are this constant. Because the value is fetched along with the instruction, it need not be read separately; it is already waiting in the instruction queue. An immediate value can only be a source, because writing to a constant is meaningless: ADD 5, AX would mean “let the new value of 5 be 5 + AX.”

A memory operand is given by an address. In MOV AX, [BX] the square brackets mean “the number in BX is an address; take the word at that address.” The processor first computes the address, then gives the bus interface unit (BIU) a read request. The BIU puts the address on the address bus, reads the data from memory, and passes it to the execution unit. This external access adds at least four clock periods compared with a register operand.

The basic rules among the three kinds are these. The two operands must be the same size: a 16-bit register cannot be moved into an 8-bit register. At most one memory operand can appear in an instruction; MOV [BX], [SI] is invalid. An immediate value cannot be loaded into a segment register (CS, DS, ES, SS). All these rules come from the 8086's instruction encoding. The instruction format has a single field that specifies a memory address; there is no room to encode a second memory operand. No opcode that loads a constant into a segment register was designed either.

Example 3.2.2

Identify the operand types of the following instructions: ADD CL, 10, MOV [BX], AX, SUB DX, counter.

ADD CL, 10: the destination is a register (CL), the source is an immediate value (10). CL ← CL + 10. There is no memory access.

MOV [BX], AX: the destination is memory, the source is a register. The two bytes of AX are written to the address BX points to, low byte first. One bus cycle (write) is needed.

SUB DX, counter: the destination is a register, the source is memory (counter is a variable name, which the assembler turns directly into an address). If counter is a DW variable, DX ← DX − [counter]; if it is a DB variable, a size-mismatch error results.

3.2.3.2Implicit operands

Some instructions, besides the operands that are written, also use or change registers that do not appear in the instruction line at all. Which registers these are is built into the definition of the instruction.

Definition 3.2.4

An implicit operand is a register or memory location that an instruction reads or changes although it is not written in the instruction line. Implicit operands are fixed in the instruction's opcode; the programmer cannot choose them and only has to know them.

Table 3.2.8: Implicit operands of some instructions.
InstructionWritten operandImplicit operand(s)Operation
MUL BLBLAL (multiplicand), AX (result)AX ← AL × BL
DIV BLBLAX (dividend), AL (quotient), AH (remainder)AL ← AX ÷ BL, AH ← AX mod BL
LOOP donagainCX (counter)CX ← CX − 1; jump if CX ≠ 0
CBW—AL → AXthe sign bit of AL is copied to all bits of AH
PUSH AXAXSS:SP (top of the stack)SP ← SP − 2; [SS:SP] ← AX
XLAT—AL (index and result), BX (table address)AL ← [DS:BX + AL]

The implicit uses in the table are also the source of the names of the 8086 registers. AX is the accumulator: the result of multiplication and division is always written there. CX is the count register: LOOP decrements it automatically, and multi-bit shifts read the count from its lower half CL. BX is the base register: XLAT looks for the start of the table there. SP points to the top of the stack and changes automatically on every PUSH and POP. The “special duties” of registers are really hardwired connections of these instructions in the hardware. One input of the multiplier circuit is connected directly to AL and its output directly to AX.

The practical consequence of implicit-operand knowledge is this: an instruction can also change a register that is not written. In the line MUL BL, AH is never mentioned, but the instruction wipes AH out, because the 16-bit result is written to the whole of AX. A value saved in AH is lost after this line. A program that wants to preserve a register's value must know the implicit operands of the instructions it uses.

Example 3.2.3

DIV BL runs with AX = 100 (0064h) and BL = 7. What are AL, AH, and AX?

In 8-bit division the dividend is implicitly the whole of AX, and the divisor is the written BL. The quotient of 100 ÷ 7 is 14 and the remainder 2 (7 × 14 = 98, 100 − 98 = 2). The quotient is written to AL and the remainder to AH: AL = 0Eh, AH = 02h. Read together, the two halves give AX = 020Eh. The value AX had before the division is lost. Had the quotient not fit in 8 bits, for example with AX = 1000 and BL = 2, the processor would have generated a divide-error interrupt (INT 0).

Example 3.2.4

CBW runs with AL = F6h. What is AX? What would the difference have been if MOV AH, 0 had done the same job?

In two's complement F6h is −10; its sign bit (bit 7) is 1. CBW copies this bit into the eight bits of AH: AH = FFh, AX = FFF6h. FFF6h is also −10 in 16 bits; the signed value is preserved. MOV AH, 0, however, gives AX = 00F6h = 246. This result is correct if AL is an unsigned number and wrong if it is signed. CBW has no written operand at all; both its source (AL) and its destination (AX) are implicit.

3.2.3.3Code trace: MUL, SHR, and LOOP

The following program uses three instructions with implicit operands in a row. In the program CX is written only once, and AX appears to be written only in the ADD line. The trace shows how many times these registers actually change.

ORG 100h
MOV AL, 12
MOV BL, 10
MUL BL         ; AX = AL × BL
MOV CL, 2
SHR AX, CL     ; count in CL
MOV CX, 3      ; LOOP counter
again:
ADD AX, 1
LOOP again     ; CX decrements
RET

At the start of the program the initial state of .COM programs applies: the general registers are 0 and the status flags are 0. Table 3.2.9 gives the state after each instruction. The address column is the instruction's relative location and the bytes column is the machine code.

Table 3.2.9: Trace of the implicit-operand program (each row is the state after the instruction executes).
AddressBytesInstructionAXBXCXCFZFComment
0100hB0 0CMOV AL, 12000Ch0000h0000h00AL = 12
0102hB3 0AMOV BL, 10000Ch000Ah0000h00BL = 10
0104hF6 E3MUL BL0078h000Ah0000h0?AX ← AL × BL = 120
0106hB1 02MOV CL, 20078h000Ah0002h0?shift count
0108hD3 E8SHR AX, CL001Eh000Ah0002h00120 ÷ 4 = 30
010AhB9 03 00MOV CX, 3001Eh000Ah0003h00the 2 in CL is overwritten
010Dh05 01 00ADD AX, 1001Fh000Ah0003h00iteration 1
0110hE2 FBLOOP again001Fh000Ah0002h00CX ≠ 0 → again
010DhADD AX, 10020h000Ah0002h00iteration 2
0110hLOOP again0020h000Ah0001h00CX ≠ 0 → again
010DhADD AX, 10021h000Ah0001h00iteration 3
0110hLOOP again0021h000Ah0000h00CX = 0 → falls through
0112hC3RET0021h000Ah0000h00result 33

The MUL step. In the line MUL BL only BL is written. The multiplicand is implicitly AL (12), and the result is implicitly AX. 12 × 10 = 120 = 0078h. Since the result fits in 8 bits, AH = 00h and CF = OF = 0 remain. On the 8086, MUL sets these two flags according to the question “is the upper half of the result significant?” SF, ZF, AF, and PF, on the other hand, are undefined after MUL: the processor writes some value into them, but Intel does not document that value. This is why a question mark is placed for ZF in the table. For a program to rely on ZF, an instruction that sets the flag in a defined way must follow.

The SHR step. To shift a register by more than one bit on the 8086, the shift count can be given only in CL. The form SHR AX, 2 arrived with the 80186. The program therefore first writes MOV CL, 2. A right shift halves the value at every bit: 0078h = 0111 1000b shifted two bits to the right becomes 0001 1110b = 001Eh = 30. The last bit shifted out is written into CF. Since the two bits shifted out are 0 and 0, CF = 0. Since the result is nonzero, ZF = 0. With this instruction ZF has become defined again.

The MOV CX, 3 step. This line writes 3 into CX. CL is the lower half of CX; the 2 written to CL in the previous step is thereby erased. The loss is unimportant because the shifting is finished, but had the order been reversed, that is, had CX been set first and then 2 written to CL, the loop would have run 2 times instead of 3. One physical register being known under two names becomes a frequent source of errors when combined with implicit operands.

The LOOP steps. The instruction LOOP again does two jobs in one instruction: it decrements CX by 1 and jumps to the label again if CX is not zero. No line in the program decrements CX, yet the trace shows CX changing three times, 3 → 2 → 1 → 0. LOOP's decrement does not affect the flags; LOOP is an instruction that does not change flags. On each iteration ADD AX, 1 increments AX by one: 30 → 31 → 32 → 33. At the third LOOP, CX drops to zero, the jump is not taken, and the flow falls through to RET.

At the end of the program AX = 0021h = 33. Read line by line, the result is not surprising, but someone who thinks AX is written only in the ADD line would miss that MUL and SHR changed AX. Figure 3.2.3 shows three moments of the trace with drawings from the slides.

AX0078hBX000AhCX0000hCF0ZF?AX = 120 (decimal)implicit: AL, AXAX001EhBX000AhCX0002hCF0ZF0AX = 30 (decimal)count in CLAX0021hBX000AhCX0000hCF0ZF0AX = 33 (decimal)
Figure 3.2.3: Three moments of the implicit-operand trace. At the top, after MUL BL: AX = 0078h, ZF undefined. In the middle, after SHR AX, CL: AX = 001Eh, CX = 0002h. At the bottom, at RET: AX = 0021h, CX = 0000h. Highlighted boxes are the registers that changed in that step.
Common mistake

Assuming MUL preserves AH. A program that keeps a counter or an intermediate result in AH loses that value when it runs MUL BL. The 16-bit MUL BX changes an even wider area: the result is written to the pair DX:AX, and the old value of DX is erased too. A register that must be preserved is moved to another register or to the stack before the MUL.

3.2.3.4Register or memory?

A value is held either in a register or in memory. The choice between the two is the decision that affects a program's speed the most. Figure 3.2.4 shows how far the two places are from the processor.

CPUAXBXCXDX0 bus cyclessystem busevery access ≥ 4 clock periodsMemory (1 MB)code · variablesarrays · stack
Figure 3.2.4: Registers are inside the CPU; memory is at the other end of the system bus. Accessing a register needs no bus cycle; every memory access is a bus cycle that lasts at least four clock periods.

The 8086 has 14 registers visible to the programmer: 8 general-purpose registers (AX, BX, CX, DX, SP, BP, SI, DI), 4 segment registers (CS, DS, ES, SS), the instruction pointer IP, and the FLAGS register. All are 16 bits. Registers are small, very fast memory cells built from flip-flops. The value of a register reaches the ALU directly over the internal bus; it never goes out onto the external lines.

Memory, on the other hand, is outside the CPU and on the 8086 can grow up to 1 MB. Program code, variables, arrays, and the stack live here. To read a word from memory, the processor has to execute a bus cycle.

Definition 3.2.5

A bus cycle is the operation in which the processor reads or writes a memory or I/O location over the system bus. On the 8086 a bus cycle consists of at least four T states (T1–T4); each T state is one clock period. If the memory is slow, wait states (Tw) are inserted between T3 and T4.

In a read cycle, at T1 the processor puts the 20-bit address on the lines AD0–AD15 and A16–A19 and has the address captured by external latches with the ALE signal. At T2 the same lines are released for data and the RD signal becomes active. At T3 the memory puts the data on the data bus. At T4 the processor takes the data and the signals are withdrawn. With a register operand none of these four steps exists. A memory access is therefore many times longer than a register access.

A memory access has one more cost. The 8086's data bus is 16 bits wide, and in one bus cycle it can read as a whole a word that starts at an even address. If the word starts at an odd address, two separate bus cycles are needed: one for the low byte and one for the high byte. In this case the access is four clock periods longer.

This difference sets the rule of good assembly code: frequently used values are kept in registers, and memory is visited only when necessary. Keeping a loop counter in CX instead of in memory makes the loop faster. The elements of an array have to stay in memory, but the sum of the elements can be accumulated in a register during the loop and written to memory once at the end.

3.2.3.5Instruction timing

The Intel 8086 data sheet gives how many clock periods each instruction takes. For instructions with memory operands, an effective address (EA) time is added to this for computing the address. The effective address is the memory operand's relative location within the segment; it can be a direct constant, a register, or the sum of a register and a constant.

Table 3.2.10: Timings of some 8086 instructions (best case, clock periods).
InstructionOperandsClock periods
MOV AX, BXregister, register2
MOV AX, 5register, immediate4
MOV AX, numaccumulator, direct memory10
MOV CX, [BX]register, memory8 + 5 = 13
ADD AX, BXregister, register3
ADD AX, numregister, memory9 + 6 = 15
INC CX16-bit register2
INC countermemory (word)15 + 6 = 21
Table 3.2.11: Time of the effective address calculation.
Address formExampleEA time (periods)
base or index only[BX], [SI]5
direct addressnum, [0200h]6
base + index[BX+SI], [BP+DI]7
base + index[BX+DI], [BP+SI]8
base or index + constant[BX+4]9

The differences in the table are due to the hardware. MOV AX, BX is an internal transfer: 2 periods. MOV AX, 5 takes 4 periods, because the 16-bit constant must be pulled from the instruction queue. MOV CX, [BX] first computes the effective address (5 periods), then executes a bus cycle. MOV AX, num is a special case. Loading AX from a direct address uses the short accumulator form (opcode A1), which carries the address inside the instruction and needs no EA calculation: 10 periods. Instructions that write to memory are the longest. INC counter first reads the word, increments it in the ALU, then writes it back; it contains two bus cycles and takes 21 periods.

The values in the table are best-case timings. A word access at an odd address adds 4 periods to each access. If the instruction queue is empty after a jump, the processor waits for the bytes to arrive. If a segment prefix is used, 2 more periods are added. The real time may therefore be longer than the table's. The ratio does not change, though: an instruction with a memory operand is several times slower than its register counterpart.

Example 3.2.5

On a 5 MHz 8086, in a loop that runs 1000 times, a counter is incremented once per iteration. How long do the increments take in total when the counter is kept in CX and when it is kept in memory?

At 5 MHz one clock period is 1 / (5 × 106) s = 0.2 µs. If the counter is in CX, each increment with INC CX takes 2 periods: 1000 × 2 = 2000 periods = 2000 × 0.2 µs = 0.4 ms. If the counter is in memory, each increment with INC counter takes 21 periods: 1000 × 21 = 21,000 periods = 4.2 ms. Only the counter's location changed, and the time grew more than tenfold. Since the other instructions of the loop remain the same, the difference in total time is also 3.8 ms.

Example 3.2.6

How many clock periods does the sequence MOV AX, 5, MOV BX, 3, ADD AX, BX, MOV CL, AL take? What would change if the second line were MOV BX, num (direct address, word)?

An immediate value into a register takes 4, register-to-register addition 3, and an 8-bit register-to-register MOV 2 periods: 4 + 4 + 3 + 2 = 13 periods; at 5 MHz, 2.6 µs. If the second line reads from memory, the accumulator form cannot be used because the destination is BX, not AX; the time becomes 8 + 6 = 14 periods. The total is 4 + 14 + 3 + 2 = 23 periods, that is, 4.6 µs. A single memory operand has roughly doubled the time of the sequence.

Common mistake

Confusing instruction length with instruction time. A short instruction is not necessarily a fast one. MUL BL is only two bytes (F6 E3) but takes 70–77 clock periods; the three-byte ADD AX, 1234h (05 34 12) takes 4. The number of bytes determines the space the instruction occupies in memory and how far IP will advance. The time is determined by the instruction's internal operation and the number of bus cycles.

3.2.4IP and the flags

3.2.4.1How does IP advance?

IP is never written in programs, yet every instruction changes it. The instruction pointer (IP) holds the relative location, within the code segment, of the next instruction. The physical address is computed from CS and IP: CS × 10h + IP. This pair is called CS:IP.

Definition 3.2.6

After an ordinary (non-jumping) instruction executes, IP advances by the instruction's length in bytes: IPnew = IPold + instruction length. Jump, call, return, and interrupt instructions, on the other hand, write a new value into IP. IP cannot be written with MOV.

8086 instructions range in length from 1 to 6 bytes. To know how far IP will advance, you must know each instruction's length. In the program below the lengths are written as comments.

ORG 100h
MOV AX, 5     ; 3 bytes
MOV BX, 2     ; 3 bytes
INC AX        ; 1 byte
ADD AX, BX    ; 2 bytes
RET           ; 1 byte
Table 3.2.12: IP trace (each row is the state after the instruction executes).
StepInstruction addressBytesInstructionIPAXBXSP
0——(loaded)0100h0000h0000hFFFEh
10100hB8 05 00MOV AX, 50103h0005h0000hFFFEh
20103hBB 02 00MOV BX, 20106h0005h0002hFFFEh
30106h40INC AX0107h0006h0002hFFFEh
40107h03 C3ADD AX, BX0109h0008h0002hFFFEh
50109hC3RET0000h0008h0002h0000h

In step 0 the program has been loaded at offset 0100h of the segment, and IP = 0100h points to the first instruction. In step 1 the processor reads the byte B8, understands that a two-byte constant follows this opcode, and takes all three bytes together. IP advances to 0103h; when the instruction executes, AX = 0005h. In step 2 the same happens for BX: 3 more bytes, IP = 0106h.

The INC AX in step 3 is a single byte. The code of the 16-bit register increment instructions is 40h + register number; for AX, 40h. IP advances by only 1: 0107h. In step 4, ADD AX, BX is two bytes: the opcode 03h and a byte that defines the operands (C3h). IP = 0109h, and AX = 0006h + 0002h = 0008h.

Step 5 is not an ordinary instruction. RET takes the word at the top of the stack into IP. When a .COM program starts, the top of the stack (SS:FFFEh) holds the 0000h that DOS placed there. RET writes this value into IP and increases SP by 2: FFFEh + 2 = 10000h, which does not fit in 16 bits, so SP = 0000h. IP = 0000h now points not to the program but to the first byte of the PSP at the start of the segment. There sits the INT 20h instruction (CD 20), which ends the program.

B8 05 000100MOVIP = 0100hBB 02 000103MOV400106INC03 C30107ADDC30109RETB8 05 000100MOVBB 02 000103MOV400106INC03 C30107ADDIP = 0107hC30109RETB8 05 000100MOVBB 02 000103MOV400106INC03 C30107ADDC30109RETIP = 0000h (return to the PSP)
Figure 3.2.5: The instruction bytes in memory and IP. At the top the program has been loaded, IP = 0100h. In the middle three instructions have executed, IP = 0107h. At the bottom RET has taken 0000h from the stack and IP has returned to the start of the PSP. The width of each box shows the instruction's byte count.

The relationship between IP and the hardware hides a subtlety here. The 8086's bus interface unit prefetches instruction bytes and holds them in a 6-byte queue. The address the BIU reads from memory is a few bytes ahead of the address of the instruction being executed. The IP the programmer sees, however, is always the address of the next instruction to be executed. When a jump occurs, the queue is flushed and the BIU starts fetching from the new IP. The queue is invisible to the programmer; it shows up only in the timings.

Example 3.2.7

A program starts at 0100h and executes in order four instructions of lengths 3, 2, 1, and 4 bytes. None of the instructions is a jump. What is IP after the fourth instruction? What is the address of the third instruction?

IP advances by the length on every instruction: 0100h → 0103h → 0105h → 0106h → 010Ah. The four instructions total 3 + 2 + 1 + 4 = 10 bytes, and IP = 0100h + 0Ah = 010Ah. The third instruction starts where the first two end, at address 0105h.

Common mistake

Advancing IP by the number of instructions. The thought “three instructions have executed, so IP is 0103h” is wrong. IP counts bytes, not instructions. Because instruction lengths on the 8086 vary, computing IP requires knowing the length of every instruction. The lengths can be read from emu8086's memory view or from the assembler's listing.

3.2.4.2Which instructions change the flags?

The flags register (FLAGS) carries information about the result of the last arithmetic or logic operation. The status flags are CF (carry), ZF (zero), SF (sign), OF (overflow), AF (auxiliary carry), and PF (parity). Conditional jump instructions decide by looking at these flags. Which instruction changes which flag therefore directly determines the flow of the program.

The basic rule is that the flags are written only by instructions that compute a result. Instructions that move data compute no result; they do not touch the flags. Table 3.2.13 groups instructions by their effect on the flags.

Table 3.2.13: Effect of instructions on the status flags.
GroupInstructionsEffect
Data movementMOV, XCHG, LEA, PUSH, POP, CBWno flags change
Loops and jumpsJMP, Jcc, LOOP, CALL, RETno flags change
NOTNOTno flags change
Increment, decrementINC, DECZF, SF, OF, AF, PF are rewritten; CF is unchanged
Addition, subtraction, comparisonADD, ADC, SUB, SBB, CMP, NEGall six status flags are rewritten
LogicAND, OR, XOR, TESTCF = OF = 0; ZF, SF, PF according to the result
MultiplicationMUL, IMULCF, OF defined; ZF, SF, AF, PF undefined
Direct settingSTC, CLC, CMCCF only

Two rows of the table are surprising. The first is NOT. NOT is a logic operation and computes a new value, but on the 8086 it changes no flag. A program that wants to test the result after NOT must follow it with TEST AL, AL or CMP. The second is INC and DEC. These two instructions do not touch CF. The aim of the design is loops working on multi-byte numbers: while the loop counter or index is changed with INC/DEC, the carry carried by ADC is not lost. To see that INC has taken a number from FFFFh to 0000h, look not at CF but at ZF.

Definition 3.2.7

The flag a conditional jump looks at shows the result of the last instruction that wrote that flag before it. Flag-preserving instructions in between, such as MOV, NOT, and LOOP, do not disturb this relationship; an INC, ADD, or CMP in between does.

3.2.4.3Code trace: the flags

The following program tests the flag rules one by one. The comment on each line tells in advance what that line does to the flags; the trace confirms these predictions.

ORG 100h
STC              ; CF = 1
MOV AL, 0FFh     ; flags kept
INC AL           ; CF untouched
MOV CX, 0        ; ZF kept
DEC AL
ADD AL, 1        ; new CF
CLC
NOT AL           ; flags kept
RET
Table 3.2.14: Flag trace (each row is the state after the instruction executes).
AddressBytesInstructionALCFZFSFOFAFPFWhich flags were written?
0100hF9STC00h100000CF only
0101hB0 FFMOV AL, 0FFhFFh100000none
0103hFE C0INC AL00h110011all except CF
0105hB9 00 00MOV CX, 000h110011none
0108hFE C8DEC ALFFh101011all except CF
010Ah04 01ADD AL, 100h110011all
010ChF8CLC00h010011CF only
010DhF6 D0NOT ALFFh010011none

STC and MOV. STC (set carry) sets CF directly to 1. It is one of the few instructions that change a flag without being the result of an operation. MOV AL, 0FFh writes 255 to AL; none of the flags changes. MOV computes no result; it only copies.

INC AL. FFh + 1 = 100h does not fit in 8 bits and AL = 00h. Had the addition been done with ADD, this carry would have been written to CF. INC does not touch CF; CF is the 1 left over from STC. Since the result is zero, ZF = 1, and since a carry passes from bit 3 to bit 4, AF = 1. The number of one bits in 00h is zero, that is, even; PF = 1. In the signed interpretation −1 + 1 = 0 is a correct result, with no overflow: OF = 0.

MOV CX, 0. Zero is written to CX. Although the result is zero, ZF is not recomputed; the 1 in ZF is left over from the previous INC. Had a JZ followed this line, the jump would have been taken, but the reason would be AL, not CX.

DEC AL. 00h − 1 = FFh. Since the top bit is 1, SF = 1, and since the result is not zero, ZF = 0. Because a borrow comes from bit 4, AF = 1, and because the eight one bits of FFh are an even count, PF = 1. In the unsigned interpretation, subtracting 1 from 0 causes a borrow. SUB would write this to CF; DEC does not, and CF stays 1.

ADD AL, 1. FFh + 1 = 100h, AL = 00h. This time ADD does the addition, and ADD rewrites all six status flags. CF = 1; the value in the table looks the same as in the previous row, but it is no longer the 1 left from STC; it is the carry ADD produced. ZF = 1, SF = 0, AF = 1, PF = 1, OF = 0.

CLC and NOT. CLC sets CF to 0. NOT AL inverts all the bits of AL: 00h → FFh. Although AL is no longer zero, ZF is still 1, because NOT writes no flags. To test after this line whether AL is zero, TEST AL, AL is needed.

AL00hCF1ZF1SF0AF1PF1CF preservedALFFhCF1ZF0SF1AF1PF1CF preservedALFFhCF0ZF1SF0AF1PF1no flags
Figure 3.2.6: Three moments of the flag trace. At the top, after INC AL: AL = 00h, ZF = 1, CF preserved. In the middle, after DEC AL: AL = FFh, SF = 1, CF again preserved. At the bottom, after NOT AL: although AL = FFh, ZF = 1 remains.
Common mistake

Not checking who set the flag before a conditional jump. Inserting a MOV AX, [BX] between DEC CX and JZ done does not disturb the flow; MOV writes no flags. Inserting an ADD SI, 2 does: JZ now looks not at CX but at the sum in SI. Before a jump, the question “which instruction wrote this flag last?” should be asked.

3.2.5The first program

3.2.5.1The .COM program template

When a new file is opened in emu8086 with COM template selected, the editor opens with an empty .COM template. The skeleton of a .COM program has only three parts: ORG 100h, which states the starting location, the instructions, and the RET that ends the program. Variables, if any, come after the RET.

ORG 100h          ; .COM: code starts at 0100h

MOV AX, 5         ; AX = 5
MOV BX, 3         ; BX = 3
ADD AX, BX        ; AX = AX + BX = 8
MOV CL, AL        ; CL = 08h

RET               ; back to DOS

num DB 0          ; variables go after RET

ORG 100h. When DOS loads a .COM program, it first picks a segment and writes a header called the PSP (program segment prefix) into the first 256 bytes of this segment (0000h–00FFh). The PSP holds the program's command line, its end address, and other information DOS uses. The program's bytes are copied right after the PSP, starting at 0100h. ORG 100h tells the assembler this fact. Without the directive, the assembler would assume the first byte is at 0000h and compute all variable addresses 256 bytes too low.

Sequential execution. Instructions execute from top to bottom in order. If there is no jump instruction, after each instruction the processor moves on to the bytes right after it in memory. Blank lines and comments add nothing to this order.

RET. When the program ends, control must return to the operating system. RET does this indirectly: it takes 0000h from the stack into IP, the processor executes the INT 20h instruction at the start of the PSP, and DOS terminates the program. If RET is forgotten, the processor cannot know that the program has ended. It goes on decoding the bytes after the instructions, that is, the variables and the random memory contents after them, as instructions.

Where variables go. That is why variables are placed at the end of the code, after the RET. The processor that reaches RET returns and never touches the bytes of the variables. If the variables are to be placed before the code, the first instruction must be a JMP that jumps over the data.

The initial state. A .COM program has a single segment: code, data, and stack are in the same 64 KB. The loader therefore puts the same value into all four segment registers: CS = DS = ES = SS. emu8086 uses 0700h for this value. IP = 0100h and SP = FFFEh; the stack starts at the very end of the segment and grows downward. At the top of the stack, at address FFFEh, sits the word 0000h that makes RET's return work. The general registers are zero.

Table 3.2.15: Initial state of a .COM program in emu8086.
RegisterValueMeaning
CS, DS, ES, SS0700hsingle segment; the segment starts at physical address 07000h
IP0100hthe first instruction after the PSP
SPFFFEhtop of the stack; [FFFEh] = 0000h
AX, BX, CX, DX, SI, DI, BP0000h—
FLAGSIF = 1, others 0interrupts enabled

The job of the four instructions in the template is simple: 5 is written to AX, 3 to BX, the two are added, and the low byte of the result is copied to CL. The purpose of the program is not a calculation but to show how a .COM program sits in memory and how it runs.

3.2.5.2Code trace: a .COM program in memory

Table 3.2.16 gives the state of the template program after each instruction. The physical address column is 07000h + the relative location for segment 0700h.

Table 3.2.16: Trace of the .COM program (each row is the state after the instruction executes).
StepInstruction (address)Physical addressAXBXCLIPSP
0(loaded)—0000h0000h00h0100hFFFEh
1MOV AX, 5 (0100h)07100h0005h0000h00h0103hFFFEh
2MOV BX, 3 (0103h)07103h0005h0003h00h0106hFFFEh
3ADD AX, BX (0106h)07106h0008h0003h00h0108hFFFEh
4MOV CL, AL (0108h)07108h0008h0003h08h010AhFFFEh
5RET (010Ah)0710Ah0008h0003h08h0000h0000h
6INT 20h (PSP, 0000h)07000hprogram ends

Steps 1–4 are ordinary instructions, and IP advances on each by the instruction length: 3, 3, 2, and 2 bytes. The addition in step 3 also writes the flags: 5 + 3 = 8, the result is nonzero (ZF = 0), the sign bit is 0 (SF = 0), and there is no carry or overflow (CF = OF = 0). Since 08h has a single 1 bit, the parity is odd and PF = 0. The MOV CL, AL in step 4 copies the low byte of AX into CL; CH is unchanged and CX = 0008h.

In step 5, RET reads a word from the stack. SS:SP = 0700:FFFEh, that is, the word at physical address 16FFEh is 0000h. This value is written to IP, and SP returns to 0000h by increasing 2. In step 6 the processor executes the two bytes at 0700:0000, CD 20, that is, INT 20h. DOS's terminate service removes the program from memory. The num byte at 010Bh was not executed in any step; it is only data.

segment 0700h0000hPSP (256 bytes)0100hMOV AX, 50103hMOV BX, 30106hADD AX, BX0108hMOV CL, AL010AhRET010Bhnum = 00⋮FFFEhstack: 0000hIP = 0100hSP = FFFEhCS:IPSS:SPAX0000hBX0000hCL00hsegment 0700h0000hPSP (256 bytes)0100hMOV AX, 50103hMOV BX, 30106hADD AX, BX0108hMOV CL, AL010AhRET010Bhnum = 00⋮FFFEhstack: 0000hIP = 0000hSP = 0000hCS:IPAX0008hBX0003hCL08h
Figure 3.2.7: The layout of the .COM program within the segment. At the top the program has been loaded: PSP at 0000h–00FFh, code from 0100h, num at 010Bh, the top of the stack at FFFEh; CS:IP points to the first instruction and SS:SP to the top of the stack. At the bottom RET has executed and control has returned to the PSP with IP = 0000h.

This trace can also be read from the point of view of the system bus. The BIU fetches the bytes of each instruction from the code segment. The physical address used for fetching is CS × 10h + IP: 07000h + 0100h = 07100h for the first byte. The program's four arithmetic instructions read no data from memory; all their operands are registers or immediate values. A bus cycle for data happens only at RET: a word is read from the stack. RET is also a jump; the instruction queue is flushed and the BIU starts fetching again from 07000h.

3.2.5.3The program in memory: byte by byte

The bytes the assembler produces from the template program are as in Table 3.2.17. A .COM file consists of exactly these bytes.

Table 3.2.17: Machine code of the template program.
Relative locationBytesSource lineDecoding
0100hB8 05 00MOV AX, 5B8 + register no. (AX = 0); constant low byte first
0103hBB 03 00MOV BX, 3B8 + 3 (BX)
0106h03 C3ADD AX, BXC3 = 11 000 011: register–register, AX, BX
0108h8A C8MOV CL, ALC8 = 11 001 000: CL, AL
010AhC3RETsingle-byte instruction
010Bh00num DB 0data; not an instruction

The first two instructions are from the “immediate value into a register” family, and the opcode contains the register number. The 16-bit register numbers of the 8086 are: AX = 0, CX = 1, DX = 2, BX = 3, SP = 4, BP = 5, SI = 6, DI = 7. Note that the order is not alphabetical; BX is number 3. For the 8-bit registers the same numbers are used in the order AL, CL, DL, BL, AH, CH, DH, BH.

The third and fourth instructions work between two registers. In these instructions the first byte defines the operation and the second byte defines the operands. The second byte is called the ModR/M byte and is divided into three fields: the 2-bit MOD, the 3-bit REG, and the 3-bit R/M. MOD = 11 means “both operands are registers.” For ADD AX, BX, the opcode 03h has the form “REG ← REG + R/M.” REG = 000 (AX) gives the destination and R/M = 011 (BX) the source. Combined, the bits give 11 000 011 = C3h. For MOV CL, AL, the opcode 8Ah has the form “8-bit REG ← R/M.” REG = 001 (CL) and R/M = 000 (AL), and 11 001 000 = C8h results.

Example 3.2.8

What are the machine codes of ADD DX, CX and MOV BL, AH?

ADD DX, CX: opcode 03h (REG ← REG + R/M), MOD = 11, REG = DX = 010, R/M = CX = 001. ModR/M = 11 010 001 = D1h. The instruction is 03 D1.

MOV BL, AH: opcode 8Ah, MOD = 11, REG = BL = 011, R/M = AH = 100. ModR/M = 11 011 100 = DCh. The instruction is 8A DC. Both instructions are two bytes; IP advances by 2 on each.

Four conclusions from the table matter. First, the .COM file is exactly these 12 bytes. There is no header; DOS copies the file's bytes into memory as they are, starting at 0100h. Second, the line ORG 100h has no bytes at all; the directive only sets the location of the first byte.

Third, the same instruction can have more than one encoding. The register–register instructions of the 8086 have a direction bit: 03h means “REG is the destination” and 01h means “R/M is the destination.” ADD AX, BX can also be written with 01h; then REG = BX, R/M = AX, and the code is 01 D8. MASM chooses 03 C3; another assembler may choose 01 D8. Both do the same job in the same time. A listing may therefore show different bytes in different assemblers.

Fourth and most important, there is no marker in memory between instruction and data. The 00 byte at 010Bh is a variable, but had the processor arrived there with IP = 010Bh, it would have decoded it as an instruction. On the 8086, 00h is the opcode of an ADD instruction, and the byte after it would be read as ModR/M. Whether a byte is an instruction or data is determined only by the flow of the program. This is why variables are placed after the RET.

Common mistake

Writing variables right below ORG 100h. In high-level languages variables are declared at the start of the program; when this habit is carried into assembly, the program does not work. num DB 0 lands at 0100h, and the processor executes the byte 00h, the start of an ADD, as its first instruction. The result is a random memory write and shifted instruction boundaries. Data is either put after the RET or jumped over with a JMP at the start of the code.

3.2.5.4The emu8086 emulator window

After the source is written, the emulate button in emu8086 assembles the program and loads it into the emulator window. Figure 3.2.8 shows the main parts of this window in a simplified drawing.

Loadreloadstep backsingle steprunregisters (H / L)AX00 05BX00 00CX00 00IP0103SPFFFEmemory07100B80710105071020007103BB0710403instruction listMOV AX, 00005hMOV BX, 00003hADD AX, BXMOV CL, ALRETscreenvarsstackflags
Figure 3.2.8: A simplified drawing of the emu8086 emulator window. At the top are the control buttons; on the left the registers with their high and low bytes; in the middle the memory with its physical addresses; on the right the instruction list. The drawing shows the moment after the first instruction of the template program has executed: AX = 0005h, IP = 0103h, and the highlighted line is the next instruction, MOV BX, 00003h.

The parts of the window are as follows:

  • Control buttons. single step executes one instruction and stops; the registers and memory that changed are visible immediately. step back undoes the last step, which makes it easy to go back to the cause of an error. run runs the program to the end, and reload loads the program again from the start.
  • Registers. Each register is shown with its high (H) and low (L) bytes separately: AX = 0005h appears as “00 05.” This layout makes it clear that AH and AL are the two halves of the same register.
  • Memory. The address column shows physical addresses: 0700:0100 = 07000h + 0100h = 07100h. The program bytes start at this address: B8, 05, 00, BB, 03 …
  • Instruction list. This is the bytes in memory translated back into instructions. The highlighted line is the next instruction, that is, the one CS:IP points to, not the one just executed. The list shows constants in hexadecimal with 5 digits: MOV AX, 00005h.
  • Extra windows. screen shows the screen output, vars the variables, stack the stack, and flags the flags, each in a separate window.

The meaning of the highlight in the instruction list often misleads beginners. In the situation in the figure the highlighted line is MOV BX, 00003h, but BX is still 0000h. This is not a mistake: the highlighted instruction has not executed yet. The next single step executes it; BX = 0003h and the highlight moves to the line ADD AX, BX. The register values are always the result of the instructions before the highlighted line.

The method of examining a program in the emulator is simple. Before each single step, predict how the next instruction will change which register and flag. Take the step and compare the prediction with the value the window shows. The trace tables in these notes are exactly the written-out form of such predictions.

Common mistake

Confusing the address in the memory column with the relative location. While the emulator's memory column shows 07100h, the program uses 0100h. 07100h is the physical address; 0100h is the relative location within the segment CS = 0700h. The instruction MOV AL, [0100h] reads the byte at 07100h, not the one at 00100h. The relationship between the two is always segment × 10h + relative location.

3.2.6Writing rules

The assembler recognizes numbers, characters, and names by how they are written. The rules are few, but forgetting one yields either an assembly error or a wrong value that is hard to notice.

Number bases. The base of a number is indicated by a letter added at its end. If there is no letter, the number is decimal. Table 3.2.18 gives the same value, 25, in four bases. The assembler converts all of them to the same byte, 19h; every one of the MOV AL, … lines becomes B0 19.

Table 3.2.18: Writing number bases (all 25).
BaseSuffixWritten asMOV AL, … code
decimalnone or d25, 25dB0 19
hexadecimalh19hB0 19
binaryb00011001bB0 19
octalo31oB0 19

The choice of base is only for readability; the processor sees no difference. When a port mask or flag pattern is written in binary, which bit is set is clear at once: 00100000b is bit 5. An address is written in hexadecimal, because segment and relative-location calculations are done in hexadecimal. Loop counts and everyday quantities are written in decimal.

Hexadecimal numbers that begin with a letter. Hexadecimal digits include the letters A–F. When FFh is written, the assembler cannot tell whether it is a number or a label named FFh; by the rule, any string that begins with a letter is a name. That is why a 0 is put in front of hexadecimal numbers that begin with a letter: 0FFh, 0B800h. The leading zero does not change the value; it only declares that the string is a number. MOV AX, 0B800h is encoded as B8 00 B8.

Characters. A character in quotes stands for its ASCII code. Since 'A' = 41h, MOV CL, 'A' and MOV CL, 41h produce the same machine code: B1 41. Character notation removes the burden of memorizing codes and makes clear what the program does. When a program that prints a digit on the screen writes ADD DL, '0', it is immediately clear that it converts a value between 0 and 9 into the character '0'–'9'.

Signed numbers. A constant with a minus sign is stored in two's complement. -1 becomes FFh in 8 bits and FFFFh in 16 bits: MOV AL, -1 = B0 FF, MOV AX, -1 = B8 FF FF. The constants that can be written into an 8-bit register lie between −128 and 255: negative values fit under the signed interpretation and large positive values under the unsigned one. MOV AL, 256 or MOV AL, -129 gives an error.

Case. The assembler is case-insensitive: mov, MOV, and Mov are the same; var1 and VAR1 are the same name. A consistent style is chosen for readability. In these notes, instructions and registers are written in upper case, and variable and label names in lower case.

Comments. Everything after the ; sign is a comment. In assembly almost every line gets a comment, because the instructions themselves do not explain the purpose. A good habit is to write in the comment not “what” the instruction does but “why” it is done. INC SI ; SI = SI + 1 gives no information; INC SI ; next element of the array does.

Common mistake

Forgetting the suffix. MOV AL, 10 and MOV AL, 10h are different values: 10 and 16. Writing a hexadecimal value without the suffix is an error where the assembler gives no complaint but the program works wrongly. A programmer who writes the screen memory segment B800h as MOV AX, B800 forgets both the suffix and the leading zero; the assembler takes B800 for an undefined name.

3.2.7Errors

3.2.7.1Operand restrictions of MOV

MOV is the most frequently used instruction and the one with which errors are most often made. Almost all the errors come from writing an operand combination that does not exist in the 8086's instruction encoding. Table 3.2.19 gives the six most common.

Table 3.2.19: Common MOV errors.
WrongWhy?Correct
MOV AL, BXsizes differ (8 ↔ 16 bits)MOV AL, BL or MOV AX, BX
MOV DS, 1234ha constant cannot be assigned to a segment registerMOV AX, 1234h · MOV DS, AX
MOV AL, [AX]only BX, SI, DI, BP in addressingMOV BX, AX · MOV AL, [BX]
MOV AL, FFhFFh is taken for a nameMOV AL, 0FFh
MOV IP, 200hIP cannot be written with MOVjump with JMP
MOV AL, 300300 > 255, does not fit in 8 bitsMOV AX, 300

Size mismatch. The two operands of MOV must be the same width, because the opcode carries a single width bit: either 8 bits or 16 bits. In MOV AL, BX it is unclear which half of a 16-bit value is to be taken. A programmer who wants the low byte writes MOV AL, BL. The reverse MOV CX, AL is wrong for the same reason; to widen an 8-bit value to 16 bits, the upper half is set separately: MOV CL, AL and MOV CH, 0.

A constant into a segment register. On the 8086, a MOV that writes to a segment register reads only from a general register or from memory. There is no form that loads an immediate value. Setting a segment to reach screen memory therefore takes two lines: MOV AX, 0B800h and MOV DS, AX.

Address register. On the 8086 only BX, BP, SI, and DI can be used inside square brackets. The reason is the R/M field of the ModR/M byte: in the memory modes these three bits encode only certain combinations of these four registers. There is no code for using AX as an address.

Writing to IP. IP cannot be the operand of any data instruction. The only way to change IP is the flow instructions: JMP, Jcc, CALL, RET, INT, and IRET. The assembler does not recognize IP as a register name; it rejects the line with a “destination cannot be a constant” or “undefined name” error.

A constant that does not fit. An 8-bit register holds at most 255 in the unsigned interpretation and −128 to 127 in the signed one. 300 needs nine bits. The assembler rejects the line; the value is written to a 16-bit register.

3.2.7.2Other syntax errors

Table 3.2.20: Other syntax errors.
WrongWhy?Correct
MOV CS, AXCS changes only with JMP, CALL, RET, INTfar jump
MOV ES, DSthere is no segment-to-segment MOVMOV AX, DS · MOV ES, AX
MOV [BX], [SI]two memory operandsMOV AL, [SI] · MOV [BX], AL
INC [BX]size is ambiguousINC BYTE PTR [BX]
MOV AL, [BX+BP]two base registers cannot be combined[BX+SI] or [BP+DI]
ADD 5, AXthe destination cannot be a constantADD AX, 5
PUSH 5not available before the 80186MOV AX, 5 · PUSH AX
SHL AX, 2on the 8086 the count can only be 1 or CLMOV CL, 2 · SHL AX, CL

Writing to CS. Changing CS with MOV would mean switching to another segment in the middle of the code; but IP stays the same and the processor continues from a random address. CS and IP have to change together. Far JMP, far CALL, far RET, INT, and IRET do this.

Segment to segment. There is no direct transfer between two segment registers. The value is carried in two steps through a general register. A memory-to-memory transfer is done the same way: an instruction has at most one memory operand, so the value is first taken into a register.

Ambiguous size. In the line INC [BX] it is not clear whether the operand is a byte or a word; no operand is a register from which the size could be inferred. The assembler therefore requires the size to be written explicitly: INC BYTE PTR [BX] or INC WORD PTR [BX]. The same rule applies to MOV [BX], 5. emu8086 also accepts the abbreviations b.[bx] and w.[bx].

Address combinations. The address forms the 8086 accepts are combinations of a base register (BX or BP), an index register (SI or DI), and a constant. Two bases ([BX+BP]) or two indexes ([SI+DI]) cannot be used together; the ModR/M byte has no code for them.

Instructions of later processors. PUSH 5 and SHL AX, 2 arrived with the 80186. When assembling for the 8086, MASM reports an error on these lines. emu8086 accepts these forms; the assembled code runs in the emulator, but on a real 8086 the processor does not recognize these bytes. In a program written for the 8086, a constant is pushed onto the stack through a register, and for a multi-bit shift the count is put in CL.

Example 3.2.9

wvar DW 1234h and bvar DB 5 are defined. Why is the line MOV wvar, bvar wrong, and how is it fixed?

The line has two errors at once. Both operands are memory, and their sizes differ (16 ↔ 8 bits). The value is carried through a register and the upper byte is zeroed separately:

MOV AL, bvar      ; AL = 05h
MOV AH, 0         ; AX = 0005h
MOV wvar, AX      ; wvar = 0005h

If bvar were a signed number, CBW would be used instead of the second line.

3.2.7.3Assembly errors and logic errors

An assembly program has two kinds of errors. Knowing the difference determines how to look for the error.

Definition 3.2.8

An assembly error (syntax error) is an error the assembler finds while translating the source. The assembler reports the line number and the reason; the program is never produced. A logic error, on the other hand, is the case where the program assembles and runs but gives a wrong result. The assembler cannot know this, because each line is valid on its own.

Table 3.2.21: Examples of assembly and logic errors.
Assembly errorLogic error
MOV AL, BX: size mismatchforgetting RET: data is taken for instructions
JMP strat: undefined labelusing JA for signed numbers
MOV AL, 300: a constant that does not fitADD instead of ADC: the carry is lost
MOV DS, 1234h: a constant into a segmentnot loading DS in an .EXE program

An assembly error is the easy kind: the assembler shows where, and the fix is usually a single line. A logic error is silent. The program runs, perhaps gives the right result for most inputs, and goes wrong only in some cases. The examples in the table are typical of this kind. JA is the jump of an unsigned comparison; when comparing −1 with 1, it counts −1 as FFFFh, a large number. A multi-byte addition done with ADD does not carry the carry from the low bytes into the high bytes. If DS is not loaded in an .EXE program, the variables are looked for in the segment where the PSP is, and entirely different bytes are read.

The way to find a logic error is single-step execution. The program is advanced instruction by instruction in the emulator. Before each step, the expected register and flag values are computed; after the step, they are compared with what the window shows. The first instruction where the values diverge is where the error lies. The error may be in this instruction itself. The instruction may also be correct; then an earlier line has left it a wrong value. emu8086's step back button eases this search: on seeing the wrong value, go back a few steps and trace where the value came from.

Example 3.2.10

A student wants to multiply the number in AL by 3 and get the result in AX, and writes this code: MOV BL, 3 · MUL BL. For AL = 7 the program gives AX = 0015h, that is, 21. When the same code runs elsewhere with AH = 12h, the student asks why AH was erased. Is this a bug?

The code is correct; the misunderstanding is in the expectation. The result of MUL is implicitly written to the whole of AX: 7 × 3 = 21 = 0015h, AH = 00h. The expectation that the 12h in AH is preserved is a logic error, but the error is not in the code; it is in the assumption that the program will keep AH. If the value in AH is needed, it is moved to another register before the MUL. Single-step execution shows this at once: after the MUL step, the AH column changes from 12 to 00.

Common mistake

Running the program as a whole and looking only at the result. Running a program that gives a wrong result with run and starting to rewrite it just moves the error somewhere else. First go step by step and find the first deviation. If single-stepping a long loop is tedious, compare the state before and after the loop, narrowing the error first to a region and then to a line.

3.2.8Exercises and solutions

The six exercises in the slides are solved below with their intermediate steps. All register and flag values were checked by running them in the emulator.

Exercise 1

With AX = 0ABCDh, what are AX, AL, and BX after MOV AH, 0?

In AX = ABCDh the high half is AH = ABh and the low half AL = CDh. MOV AH, 0 writes only to AH: AH = 00h. AL is left untouched. The result is AX = 00CDh, AL = CDh. BX is neither written nor implicit in the instruction; its value stays whatever it was. This instruction is the shortest way to widen an unsigned 8-bit value to 16 bits.

Exercise 2

With AX = 1234h and BL = 03h, what is AX after MUL BL? What happens to the 12h in AH?

In 8-bit MUL the multiplicand is implicitly not AX but AL: AL = 34h = 52. 52 × 3 = 156 = 009Ch. The result is implicitly written to the whole of AX; AH = 00h, AL = 9Ch. The 12h in AH is erased. Since the upper half is zero, CF = OF = 0. Someone who thinks all of AX is multiplied by 3 finds 1234h × 3 = 369Ch; that result needs MUL BX and is written to DX:AX.

Exercise 3

On an 8 MHz 8086, in a loop that runs 2000 times, if the counter is incremented with INC CX (2 periods) instead of INC counter (21 periods), how many clock periods and how many milliseconds are saved?

The saving per iteration is 21 − 2 = 19 clock periods. Over 2000 iterations, 2000 × 19 = 38,000 clock periods are saved. At 8 MHz one clock period is 1 / (8 × 106) s = 0.125 µs. The saving is 38,000 × 0.125 µs = 4750 µs = 4.75 ms.

Exercise 4

With AL = 80h, what are AL, CF, ZF, SF, and OF after ADD AL, 80h?

80h + 80h = 100h. The result needs nine bits; the low eight bits are written to AL: AL = 00h. The ninth bit goes to CF: CF = 1. The result is zero: ZF = 1. The top bit is 0: SF = 0. In the signed interpretation 80h = −128, and −128 + (−128) = −256 does not fit in the 8-bit range (−128 … 127): OF = 1. In addition, PF = 1 because the number of one bits in 00h is even, and AF = 0 because there is no carry out of bit 3.

Exercise 5

The program starts at 0100h: what is IP after four instructions of 3 + 2 + 1 + 4 bytes have executed?

Since there are no jumps, IP advances by the length on every instruction: 0100h → 0103h → 0105h → 0106h → 010Ah. The total is 10 bytes = 0Ah, so IP = 0100h + 0Ah = 010Ah.

Exercise 6

Why are MOV CX, AL and MOV ES, 0B800h wrong? What are their correct forms?

MOV CX, AL: the operands are of different sizes (16 ↔ 8 bits). If the aim is only to copy the low byte, write MOV CL, AL. If the value of AL is wanted in the whole of CX as an unsigned number, the upper half is also zeroed: MOV CL, AL · MOV CH, 0.

MOV ES, 0B800h: an immediate value cannot be loaded into a segment register. The value is carried through a general register: MOV AX, 0B800h · MOV ES, AX.

3.2.9Summary

  • Assembly language is a low-level language that maps one-to-one onto machine code. Each instruction line is translated into a single machine instruction: MOV AX, 5 = B8 05 00. It produces small and fast code and accesses the hardware directly, but it is not portable.
  • The assembler translates mnemonics into opcodes and names into addresses. emu8086 combines an editor, an assembler, and an emulator; it shows the registers, memory, and flags step by step.
  • The line structure is [label:] instruction destination, source ; comment. The destination is on the left; the source does not change. The assembler is case-insensitive; comments do not enter the machine code.
  • Directives (ORG, EQU, END) produce no machine instruction; they give information to the assembler. DB and DW produce only data bytes. A macro call stands for several instructions.
  • A name begins with a letter or an underscore; reserved words cannot be names. A code label ends with a colon and denotes an address; a variable name carries an address and a type together.
  • Operand types: register (fastest), immediate value (source only), and memory (needs a bus cycle, at most one per instruction). The two operands must be the same size.
  • Implicit operands are not written in the instruction but are changed: MUL writes AX, DIV writes AL and AH; LOOP decrements CX; CBW fills AH; PUSH changes SP.
  • A memory access is a bus cycle of at least four T states. Instructions with memory operands, with the effective address time, take several times longer than their register counterparts: INC CX takes 2 and INC counter 21 periods.
  • IP is the relative location of the next instruction and advances by the instruction length. Only flow instructions write a new value into IP.
  • MOV, XCHG, LEA, PUSH, POP, NOT, and LOOP do not change the flags. INC and DEC do not touch CF. ADD, SUB, and CMP rewrite all six status flags. After MUL, ZF, SF, AF, and PF are undefined.
  • A .COM program starts at 0100h with ORG 100h; the first 256 bytes are the PSP. Initially CS = DS = ES = SS, IP = 0100h, SP = FFFEh. RET returns, through the 0000h on the stack, to the INT 20h in the PSP. Data goes after the RET.
  • There is no marker in memory between instruction and data; the flow of the program determines the meaning of a byte. The same instruction can have more than one valid encoding.
  • The assembler finds assembly errors; a logic error can be found only by single-stepping and comparing the expected values with those in the emulator.

3.2.10Key terms

  • assembly language
  • mnemonic
  • instruction
  • opcode
  • operand
  • implicit operand
  • immediate value
  • comment
  • label
  • variable
  • directive
  • constant (EQU)
  • location counter ($)
  • macro
  • assembler
  • emulator
  • .COM program
  • program segment prefix (PSP)
  • accumulator
  • counter register
  • bus cycle
  • T state
  • clock cycle
  • effective address (EA)
  • instruction pointer (IP)
  • flags register (FLAGS)
  • ModR/M byte
  • little-endian
  • single-step
  • syntax error / logic error

3.2.11Test Yourself

  1. The instructions STC, MOV AX, 0FFFFh, INC AX run in order. What are AX, CF, and ZF at the end?

    Answer

    FFFFh + 1 = 10000h does not fit in 16 bits, and AX = 0000h. The result is zero: ZF = 1. INC does not touch CF; CF is the 1 left from STC. Since MOV also changes no flags, the CF = 1 was never disturbed. Had the same addition been done with ADD AX, 1, CF would also be 1, but this time because of the carry out.

  2. In a program that begins with ORG 100h there are, in order, the lines MOV AL, 5, MOV BX, 1234h, INC BX, RET, and data DB 9. What are the bytes of the program, and what is the relative location of data?

    Answer

    MOV AL, 5 = B0 05 (0100h), MOV BX, 1234h = BB 34 12 (0102h), INC BX = 43 (0105h; 40h + 3), RET = C3 (0106h), data = 09 (0107h). The instructions are 2 + 3 + 1 + 1 = 7 bytes; data is at 0100h + 7 = 0107h. The program is 8 bytes in total, and at the end BX = 1235h.

  3. In the best case, how many clock periods and how many microseconds do the instructions MOV AX, [BX+SI] and ADD [BX], AX take on a 5 MHz 8086? (A read from memory into a register takes 8 + EA, and an addition into memory 16 + EA periods.)

    Answer

    For [BX+SI], EA = 7 periods: MOV takes 8 + 7 = 15 periods. For [BX], EA = 5 periods: ADD takes 16 + 5 = 21 periods. The total is 36 periods; at 5 MHz, 36 × 0.2 µs = 7.2 µs. The reason ADD takes long is that it both reads and writes memory: two bus cycles.

  4. With AX = 25, MOV BL, 4 and DIV BL run. What are AL, AH, and AX?

    Answer

    The dividend is implicitly AX = 25. 25 ÷ 4 = 6, remainder 1. The quotient is written to AL and the remainder to AH: AL = 06h, AH = 01h, AX = 0106h. Someone who reads AX as a single number sees 262; after DIV the two halves of AX carry separate meanings.

  5. How many lines of the following program produce bytes, and how many bytes is the program? ORG 100h · k EQU 5 · MOV AX, 5 · MOV BX, k · MOV AL, num · RET · num DB 0 · END. What are the bytes of the line MOV AL, num?

    Answer

    ORG, EQU, and END produce no bytes. Three MOVs of 3 bytes each, RET of 1 byte, DB of 1 byte: five lines, 11 bytes. num is at 0100h + 10 = 010Ah. MOV AL, num is the accumulator form that reads from a direct address into AL: A0 0A 01.

  6. MOV AL, 0F0h, ADD AL, 20h, MOV BL, AL, NOT BL run. What are AL, BL, CF, and ZF at the end?

    Answer

    F0h + 20h = 110h: AL = 10h, CF = 1, ZF = 0. With MOV, BL = 10h; the flags do not change. NOT BL = EFh; NOT changes no flags either. The result is AL = 10h, BL = EFh, CF = 1, ZF = 0. The flags are as ADD left them.

  7. In emu8086, single step is pressed three times in the template program (MOV AX, 5, MOV BX, 3, ADD AX, BX, MOV CL, AL, RET). Which line is highlighted in the instruction list, and what are IP and AX? At which physical address does the first byte of this instruction appear in the memory column?

    Answer

    Three instructions have executed: AX = 0008h, BX = 0003h. IP = 0100h + 3 + 3 + 2 = 0108h. The highlighted line is the next instruction, MOV CL, AL; CL is still 00h. The physical address is 07000h + 0108h = 07108h; the byte 8A appears there.

  8. What are the machine codes of MOV DX, 0Ah and INC CX? If the two are consecutive and start at 0103h, at which address does the next instruction start?

    Answer

    The register number of DX is 2. MOV DX, 0Ah = B8h + 2 = BAh with the constant low byte first: BA 0A 00 (3 bytes). INC CX = 40h + 1 = 41 (1 byte). The two instructions are 4 bytes; the next instruction starts at 0103h + 4 = 0107h.

  9. A program sets up a shift count with MOV CL, 3, then sets up a loop counter with MOV CX, 10, and at the end writes SHL AX, CL. Does the program assemble? By how many bits does AX shift?

    Answer

    The program assembles; every line is valid. But CL is the lower half of CX. MOV CX, 10 makes CL 0Ah, and the shift is 10 bits, not 3. This is a logic error. The shift count must be written to CL right before the shift.

3.2.12Further reading

  • The emu8086 documentation, 8086 assembler tutorial for beginners: number systems, memory access, variables, and the instruction set reference; it is the source closest to emu8086 syntax.
  • B. B. Brey, The Intel Microprocessors (8th ed.), Chapters 4 and 6: data movement instructions, ModR/M encoding, and the structure of .COM and .EXE programs.
  • M. A. Mazidi, J. G. Mazidi, The 80x86 IBM PC and Compatible Computers, Chapters 1–2: the structure of an assembly program, directives, sample programs, and working with a debugger.
  • Intel, 8086 16-Bit HMOS Microprocessor data sheet: the T states of the bus cycle and the table of instruction timings.

3.2.13References

  1. The emu8086 documentation, 8086 assembler tutorial for beginners (part 1: numbering systems, part 2: memory access).
  2. Intel, 8086 16-Bit HMOS Microprocessor data sheet.
  3. B. B. Brey, The Intel Microprocessors, 8th edition, Pearson.
  4. M. A. Mazidi, J. G. Mazidi, The 80x86 IBM PC and Compatible Computers, Pearson.

Related pages: Chapter 3.2 slides · © Sercan Külcü. All rights reserved.