Microprocessors · Lecture Notes

Chapter 4.1: Memory Access

Most of what an 8086 program does is to bring a value from memory into a register or to put a value in a register back into memory. Addition, comparison, printing text on the screen, and walking through an array cannot be done without these moves. Which byte in memory the processor reaches is decided by the square brackets inside the instruction. These notes describe what may be written inside the square brackets, that is, the addressing modes. From the base and index registers and a displacement, an effective address is computed. The effective address combines with a segment register and becomes the 20-bit physical address put on the address bus. Which segment is chosen can send the same relative location to an entirely different byte. The notes do this calculation in both directions and show how a segment override changes the default segment. Next come the size of an access (byte or word), byte order, and the rules of the MOV and XCHG instructions. Example programs are traced step by step at the register and memory level; the last example writes a letter directly into the memory of the color text screen.

Learning outcomes

Build a valid memory operand
Form the 24 memory addressing forms of the 8086 from BX, BP, SI, DI and a displacement; tell invalid combinations apart and explain why they are invalid.
Name the addressing modes
Recognize the immediate, register, direct, register indirect, based, indexed, and based-indexed modes, as well as the string, I/O, and relative modes, with examples; choose the mode that suits a data structure.
Compute addresses
Compute the effective address with 16-bit wraparound; go from segment:offset to the physical address and from the physical address to the possible segment:offset pairs; find the memory capacity from the number of address lines.
Choose the segment correctly
Apply the default-segment rule (SS if BP is present, otherwise DS); explain the effect of a segment override on the machine code and the trap of accessing data through BP.
Size and byte order
Specify the access size with byte ptr and word ptr; read the layout of words in memory in little-endian order; convert an index into a byte offset in a word array.
Trace programs with MOV and XCHG
Tell valid operand combinations apart; trace copy, swap, and video-memory programs step by step at the register, memory, and IP level.

4.1.1Memory operands

4.1.1.1Square brackets and address registers

The 8086 has fourteen registers, and only eight of them are used for general work. A program's data, on the other hand, mostly sits in memory: variables, arrays, tables, the contents of the screen, the stack. To work with this data the processor goes to memory every time, reads the byte or word it wants, and writes the result back to memory when it is done. So the first step in learning an instruction set is learning how an instruction says which memory cell it means.

In assembly language a memory cell is denoted with square brackets. The instruction MOV AX, BX copies the number in BX into AX. The instruction MOV AX, [BX], on the other hand, uses the number in BX as an address; it reads the word at that address from memory and puts it into AX. The square brackets mean “the place pointed to by what is inside.” Compared with pointer notation in C, BX is the pointer itself and [BX] is like *p.

On the 8086 not every register can be written inside square brackets. Only four registers can hold a memory address: BX, BP, SI, and DI. Of these, BX and BP are called base registers and SI and DI index registers. A base register usually holds the start address of a block of data, for example an array or a record. An index register counts the position within this block. A constant number written in the instruction can also be added to these four registers. The constant is called the displacement.

The source of this restriction is the hardware. In the instruction's machine code, only a three-bit field tells how the memory operand is to be computed. Three bits mean eight options, and the designers of the 8086 allotted these eight options to the most useful combinations of BX, BP, SI, and DI. AX, CX, DX, and SP are not on this list. That is why, however natural a notation such as MOV AL, [CX] may look, the assembler rejects it; the processor has no circuit to produce such an address.

Definition 4.1.1

The rule that determines where an instruction's operand is found and how its address is computed is called the addressing mode. On the 8086 the address of a memory operand is written inside square brackets. The address is the sum of three parts: a base register (BX or BP), an index register (SI or DI), and a displacement. Each of these three parts is optional, but at least one must be present.

4.1.1.2Twenty-four combinations

All the permitted combinations of the base, index, and displacement parts are collected in Table 4.1.1. The rows of the table show the register part and the columns the size of the displacement. d8 means an 8-bit and d16 a 16-bit displacement.

Table 4.1.1: The 24 memory addressing forms of the 8086. The row determines the register part and the column the size of the displacement.
Register(s) only+ d8+ d16
[BX + SI][BX + SI + d8][BX + SI + d16]
[BX + DI][BX + DI + d8][BX + DI + d16]
[BP + SI][BP + SI + d8][BP + SI + d16]
[BP + DI][BP + DI + d8][BP + DI + d16]
[SI][SI + d8][SI + d16]
[DI][DI + d8][DI + d16]
d16 (direct address)[BP + d8][BP + d16]
[BX][BX + d8][BX + d16]

The eight rows of the table correspond to the eight values of the three-bit field in the machine code. This field is called R/M and sits in the lowest three bits of the instruction's second byte, the ModR/M byte. The highest two bits of the same byte are the MOD field; it selects which column of the table is used. MOD = 00 means no displacement, MOD = 01 means d8 is present, and MOD = 10 means d16 is present. MOD = 11 shows that the operand is not memory but a register. Three columns times eight rows make 24; all the memory addressing forms of the 8086 are in these 24 cells.

One row looks odd. The first cell of the seventh row does not have [BP]; in its place is d16, that is, only a constant address. The designers allotted the combination R/M = 110 and MOD = 00 to direct addressing: the address of an instruction such as MOV AL, [1234h] is written with this code. No code was left for [BP] without a displacement. If the programmer writes MOV AL, [BP], the assembler quietly encodes it as [BP + 0], that is, with MOD = 01 and d8 = 00. The instruction grows by a byte but works correctly. Table 4.1.2 shows the machine code the assembler produces for a few instructions.

Table 4.1.2: Machine code of the same MOV AL, … instruction with different memory operands. The second byte is the ModR/M byte.
InstructionMachine codeMODR/MLength
MOV AL, [BX+SI]8A 00000002 bytes
MOV AL, [BX+DI]8A 01000012 bytes
MOV AL, [BP+SI]8A 02000102 bytes
MOV AL, [BP+DI]8A 03000112 bytes
MOV AL, [SI]8A 04001002 bytes
MOV AL, [DI]8A 05001012 bytes
MOV CL, [1234h]8A 0E 34 12001104 bytes
MOV AL, [BX]8A 07001112 bytes
MOV AL, [BP]8A 46 00011103 bytes
MOV AL, [BX+5]8A 47 05011113 bytes
MOV AL, [BX+128]8A 87 80 00101114 bytes

The opcode 8A in the table means “move a byte from memory or a register to an 8-bit register.” The middle three bits of the ModR/M byte (the REG field) select the destination register: 000 for AL, 001 for CL. For example, the bits of 0E = 00 001 110 read as MOD = 00, REG = 001 (CL), R/M = 110 (direct address). MOV CL, [1234h] is therefore four bytes: the opcode, the ModR/M, and a two-byte address. The address is written low byte first, like all multi-byte numbers on the 8086: 34 12. If an instruction with a direct address loads into AL or AX, the assembler chooses a shorter special form: MOV AL, [1234h] is encoded in three bytes as A0 34 12.

4.1.1.3The combination rule

The structure of the table can be reduced to a few simple rules. Once these rules are memorized, you can tell whether a notation is valid without looking at the table. Figure 4.1.1 shows the rule as a three-column choice: at most one item is taken from each column.

BaseBXBPnoneIndexSIDInoneDisplacementd8d16none++at most one choice from each column · SS if BP is chosen, otherwise DS
Figure 4.1.1: A valid memory operand is built with at most one choice from each of the columns base (BX, BP, or none), index (SI, DI, or none), and displacement (d8, d16, or none).
Definition 4.1.2

The combination rule. A memory operand contains at most one base register (BX or BP) and at most one index register (SI or DI). At most one displacement is added to them. BX and BP, or SI and DI, cannot be used together in the same address. The order in which the parts are written does not matter.

The default segment rule. If BP is in the address, the access goes to the SS (stack) segment; otherwise to the DS (data) segment.

The essence of the segment concept is this: the 8086 sees memory through 64 KB windows, and a segment register tells on every access which window to use. DS is used for data and SS for the stack. Since BP was designed to access data on the stack, addresses built with it automatically go to the SS window. The four examples in the slides apply these rules:

  • [BX+5]: base + d8. No BP, segment DS.
  • [BX+SI]: base + index. Segment DS.
  • [DI+BX-4]: the assembler reads this as [BX+DI-4]. The order does not matter; the machine code is 8A 41 FC. Here FC is the 8-bit two's complement of −4. Segment DS.
  • [BP+SI+300]: base + index + d16. Since 300 does not fit in the range −128…127, a 16-bit displacement is needed. Since BP is in the address, the segment is SS.

4.1.1.4Displacement

The displacement is a signed constant added to the address calculation and held inside the instruction's machine code. Its 8-bit form (d8) carries values between −128 and +127, and its 16-bit form (d16) values between −32,768 and +32,767. Because in 16-bit addition −1 and FFFFh give the same result, d16 actually covers the whole range 0000h–FFFFh. Example values: for d8, 22, 55h, −1; for d16, 300, 5517h, −259.

The source of the displacement is either a number or the relative location of a variable. When [BX + arr] is written, the assembler puts the address of the name arr within the segment, that is, its relative location, as the displacement. If the notation contains more than one constant, the assembler adds them into a single number at assembly time: [BX + 2 + 3] is the same instruction as [BX + 5]. The constant can be written inside or outside the square brackets; the notations [BX+5], 5[BX], and [BX]+5 all produce the bytes 8A 47 05. The C-like notation arr[SI] comes from this flexibility. The constant can also be negative: the instruction [SI-1] accesses the byte one before the one SI points to and is encoded as 8A 44 FF.

The assembler decides which of the two forms to choose by looking at the value. If the value is in the range −128…127, the short form (d8) is chosen and the instruction is a byte shorter. Otherwise the long form (d16) is needed. [BX+127] is three bytes (8A 47 7F) and [BX+128] is four bytes (8A 87 80 00). The number 128 fits in 8 bits but would be read as −128 when signed; that is why the 16-bit form is used. Since the relative location of variable names is usually greater than 127, notations such as arr[SI] almost always use d16.

[BX − 2]FEhd8 = −2extendFFFEhBX = 0100h→ EA = 00FEh0100h + FFFEh = 1 00FEh: bit 17 is discarded (16-bit wraparound)d8 for −128 … +127 (1 byte), d16 otherwise (2 bytes)
Figure 4.1.2: Before joining the addition, an 8-bit displacement is extended to 16 bits according to its sign: FFh becomes FFFFh, not 00FFh, and acts like −1.

The processor performs sign extension on an 8-bit displacement before adding it to 16-bit registers. If the highest bit is 1, the upper byte is filled with FFh, and if 0, with 00h (Figure 4.1.2). FC thus becomes FFFCh. Adding FFFCh to a number is the same as subtracting 4 once the carry that overflows the 16-bit limit is discarded.

This last point is a general property of address calculation. The effective address is always computed in 16 bits, and if the result does not fit in 16 bits, the overflowing bit is discarded; the address wraps around. With BX = FFFFh, the access [BX+2] goes not to 10001h but to 0001h. The 8086 does not carry an address overflowing the end of a segment into the next segment; it returns it to the start of the same segment.

Example 4.1.1

With SI = 0010h, from which relative location does the instruction MOV AL, [SI+0FFF8h] read?

The addition gives 0010h + FFF8h = 1 0008h. The 17th bit of the result is discarded and the effective address is 0008h. FFF8h is the 16-bit two's complement of −8; the instruction actually goes to the same place as [SI-8]. The assembler notices this too and chooses the short form: both notations produce the bytes 8A 44 F8. The processor turns the byte F8 back into FFF8h by sign extension.

4.1.1.5Valid and invalid notations

The combination rule serves for quickly testing the validity of a notation. Table 4.1.3 collects the examples from the slides together with the reasons the invalid ones are invalid. The assembler reports an error for every invalid line.

Table 4.1.3: Valid and invalid memory operands.
NotationStatusExplanation
[BX]validregister indirect, DS
[1234h]validdirect address, DS
[SI+10]validindexed, d8, DS
[BP+DI-2]validbased-indexed, d8, SS
ES:[BX+SI]validwith a segment override, ES
[AX], [CX], [DX]invalidthese registers cannot be used in address calculation
[BL], [BH]invalidan 8-bit register cannot hold a 16-bit relative location
[BX+BP]invalidtwo base registers
[SI+DI]invalidtwo index registers
[SP], [BX*2]invalidnot on the 8086; present in 32-bit addressing on the 80386 and later

The last row often causes confusion. On today's x86 processors, notations such as [ESP+4] or [EBX+ESI*4] are valid. They are part of the 32-bit addressing that came with the 80386. In the 8086's 16-bit ModR/M table there is neither SP nor a scale factor. To reach a value on the stack, SP is first copied to BP, and then [BP+n] is used.

Common mistake

Falling into the forbidden combination when wanting to use the sum of two registers as an address. MOV AX, [SI+DI] is invalid. If one of the two index registers is first copied to a base register, the job is done: MOV BX, SI followed by MOV AX, [BX+DI]. The same route works for [BX+BP]: one of BP or BX is transferred to SI or DI. In the copy, which register is chosen can also change the default segment; an address with BP goes to SS.

4.1.2Types of addressing modes

4.1.2.1Where does the operand live?

The twenty-four combinations cover all the cases where the operand is in memory. But an instruction's operand does not have to be in memory. A constant can be written directly into the instruction, or the operand can sit in a register. Books therefore name the addressing modes according to the question “where is the operand?” Table 4.1.4 gives the classification in the slides.

Table 4.1.4: Types of addressing modes for data operands. The last column shows that in modes without BP the default segment is DS.
ModeExampleWhere is the operand?
ImmediateMOV AX, 5inside the instruction (constant)
RegisterMOV AX, BXin a register
DirectMOV AX, [1000h]DS:1000h
Register indirectMOV AX, [BX]DS:BX
BasedMOV AX, [BP+4]SS:BP+4
IndexedMOV AL, [SI+3]DS:SI+3
Based-indexedMOV AL, [BX+DI]DS:BX+DI
Based-indexed + displacementMOV AL, [BX+SI+8]DS:BX+SI+8

In immediate mode the operand is the instruction itself. The machine code of MOV AX, 5 is B8 05 00; the number 5 sits in the last two bytes of the instruction. The processor has already read this value while fetching the instruction and does not go to memory a second time. An immediate value can only be a source. Since nothing can be written into a constant, MOV 5, AX is meaningless.

In register mode the operand is inside the processor. The instruction MOV AX, BX completes inside the execution unit without ever going out onto the data bus. It is therefore the fastest mode; on the 8086 it takes 2 clock periods. It is selected by writing MOD = 11 in the ModR/M byte: MOV AX, BX = 8B C3, that is, the bits C3 = 11 000 011.

All the remaining modes go to memory. In these the processor first computes an effective address (EA). The effective address is the operand's location within the segment, that is, a relative location. Then this relative location is combined with the segment register:

physical address = segment × 10h + EA

The names of the modes describe how the effective address is built. In direct mode the EA is the 16-bit constant inside the instruction. In register indirect mode the EA is the contents of a register (BX, BP, SI, or DI). In based mode the EA is the sum of BX or BP and a displacement. In indexed mode SI or DI is used instead of the base. In based-indexed mode a base and an index are added, and an optional displacement is added to that. Naming differs slightly among books. Some call [BX+4] “register relative,” others “based.” But the calculation is the same everywhere.

Definition 4.1.3

The effective address (EA) is, for a memory operand, the 16-bit sum of the base register, index register, and displacement in square brackets. If the sum exceeds FFFFh, the overflowing bit is discarded. The EA is the relative location within the segment. The physical address is the 20-bit address obtained by adding the EA to 16 times the chosen segment register.

4.1.2.2String, I/O, and relative modes

There are three more modes. They do not use the square-bracket notation. The operand is either not written in the instruction at all, or it lives in an address space separate from memory, or the address is computed relative to IP.

In string mode the operands are implicit. The instruction MOVSB moves a byte from address DS:SI to address ES:DI with no operand written beside it. The source is always DS:SI and the destination always ES:DI. After each operation SI and DI advance automatically. They increase if the direction flag DF = 0 and decrease if DF = 1. The step is 1 for a byte operation and 2 for a word operation. The details of string instructions are a separate topic. What matters here is that in these instructions the address calculation has the same structure as register indirect mode, and that the destination is looked for in the ES segment, not DS.

MOVSB           ; ES:[DI] ← DS:[SI], then SI and DI advance by one

In I/O mode the operand is an input/output port. The 8086's ports live in their own 64 K address space, separate from memory. When the processor accesses a port, it puts the port number on the address bus and makes the M/IO̅ line 0. Thus I/O devices, not memory chips, respond. Data passes only through AL or AX. If the port number is in the range 0–255, it can be written inside the instruction. Larger numbers are put in DX.

IN  AL, 45h      ; read a byte from port 45h
OUT DX, AX       ; write AX to the port in DX

In relative mode the instruction holds not the target itself but a signed displacement to be added to IP. Jump instructions use this mode. The new IP is the sum of the address of the instruction right after the jump and the displacement. In short jumps the displacement is 8 bits and reaches the range −128…+127 bytes. For example, a JNZ again at the end of a loop can be encoded as 75 FA. FA is the 8-bit two's complement of −6. Since the instruction is two bytes, the jump goes 4 bytes back from the start of the instruction. Relative addressing has a big advantage: even if the program is moved elsewhere in memory, the displacements do not change.

JNZ again       ; 75 FA: IP ← address of the next instruction − 6
Common mistake

Carrying the notation of other processors over to the 8086. Instruction names are written joined: MOVSB is correct, MOVS B is not. In the OUT instruction the port comes first and then the data register: OUT 50h, AL. The notation IN A, 45 belongs to the 8085 processor. On the 8086 the accumulator is called AL or AX, and hexadecimal numbers are written with the h suffix.

4.1.2.3Code trace: six addressing modes

The small COM program below reads values from the same six-byte table with different modes. The result of each step is given in the trace table.

ORG 100h
MOV BX, OFFSET table
MOV SI, 2
MOV AH, 7          ; immediate
MOV AL, [table+1]  ; direct
MOV CL, [BX]       ; indirect
MOV CH, [BX+4]     ; based
MOV DL, [BX+SI]    ; base+index
MOV DH, [BX+SI+3]  ; + d8
RET
table DB 11h,22h,33h,44h,55h,66h

The line ORG 100h tells the assembler that the program will start at relative location 0100h. In COM programs code, data, and stack are in the same 64 KB segment. emu8086 loads this segment at paragraph 0700h: CS = DS = ES = SS = 0700h. Adding up the instruction lengths, RET falls at 0115h and table at 0116h. The six bytes of the table are at relative locations 0116h–011Bh; their physical addresses are 07116h–0711Bh.

The OFFSET operator in the line MOV BX, OFFSET table gives not the contents of the variable but its relative location. This value is known at assembly time and is written into the instruction as an immediate value: BB 16 01. As a result BX = 0116h. BX is now a pointer to the start of the table. MOV SI, 2 puts 2 into the index register.

Table 4.1.5: Trace of the six addressing modes (DS = 0700h, BX = 0116h, SI = 0002h; table = 11 22 33 44 55 66).
InstructionMachine codeModEAPhysicalResult
MOV AH, 7B4 07immediate——AH = 07h
MOV AL, [tablo+1]A0 17 01direct0117h07117hAL = 22h, AX = 0722h
MOV CL, [BX]8A 0Fregister indirect0116h07116hCL = 11h
MOV CH, [BX+4]8A 6F 04based011Ah0711AhCH = 55h, CX = 5511h
MOV DL, [BX+SI]8A 10based-indexed0118h07118hDL = 33h
MOV DH, [BX+SI+3]8A 70 03based-indexed + d8011Bh0711BhDH = 66h, DX = 6633h

Read one by one, the difference of each mode is plain. MOV AH, 7 is immediate mode: the number 7 is the second byte of the instruction B4 07, and memory is not visited separately. MOV AL, [table+1] is direct mode. The assembler computes the expression table+1 as 0116h + 1 = 0117h and embeds this address in the instruction. The instruction takes its short accumulator form, A0 17 01. The byte at 0117h is 22h, the second element of the table. Since AH was set to 07h earlier, AX = 0722h.

MOV CL, [BX] is register indirect mode. The address is not written in the instruction; the processor takes it from BX at run time. EA = 0116h and the byte read is 11h. MOV CH, [BX+4] is based mode: EA = 0116h + 4 = 011Ah, and the value read is 55h, the fifth element of the table. CX = 5511h. The difference between these two instructions is the addition of a constant offset. When accessing the fields of a record, BX holds the start of the record and the displacement the position of the field within the record.

MOV DL, [BX+SI] is based-indexed mode: EA = 0116h + 0002h = 0118h, DL = 33h. The last instruction adds an 8-bit displacement to that: EA = 0116h + 2 + 3 = 011Bh, DH = 66h. Since BP is used in none of these six accesses, the segment is always DS. The physical address is found as DS × 10h + EA = 07000h + EA.

table (DS:0116h …)11h011622h011733h011844h011955h011A66h011Bbase + index + d8EA = BX + SI + 3 = 011Bhphysical = 07000h + 011Bh = 0711BhAH07hAL22hCL11hCH55hDL33hDH66h
Figure 4.1.3: The last step of the six addressing modes: MOV DH, [BX+SI+3] reads the byte whose effective address is 011Bh, that is, the last element of the table (66h).

The final state of the program is AX = 0722h, BX = 0116h, CX = 5511h, DX = 6633h, SI = 0002h. RET pulls the value 0000h from the stack and IP = 0000h. At relative location 0000h of the segment where the COM program was loaded sits the INT 20h instruction placed by DOS, and the program ends. Since the MOV instructions do not change the flags, the flags stay as at the start throughout the trace: only IF = 1.

4.1.3Effective address calculation

4.1.3.1Step by step: with DS

The effective address calculation is done with an addition inside the execution unit (EU). The result is handed to the bus interface unit (BIU) to be combined with the segment register. The BIU's own adder shifts the segment left by 4 bits, adds the EA, and puts the 20-bit address on the lines A19–A0. These two stages can be followed with an example:

MOV AL, [BX + SI + 4]   ; DS = 1000h, BX = 0200h, SI = 0030h
  1. Take the base register BX = 0200h.
  2. Add the index register SI = 0030h: 0230h.
  3. Add the 8-bit displacement +4.
  4. EA = 0200h + 0030h + 0004h = 0234h. The addition is 16-bit; there is no overflow here.
  5. Since BP is not in the address, the segment is DS. Physical address = 1000h × 10h + 0234h = 10000h + 0234h = 10234h. AL takes the byte at this address.
BX0200+ SI0030+ d80004EA0234Physical addressDS × 10h = 10000h+ EA = 0234h10234hAL ← [10234h]
Figure 4.1.4: The effective address and physical address for MOV AL, [BX + SI + 4]: BX + SI + 4 = 0234h; with DS = 1000h, 10234h.

Multiplying the segment by 10h means appending a zero on the right in hexadecimal: 1000h → 10000h. In binary, this means shifting the 16-bit number left by 4 bits and putting 0 into the lowest four bits. The physical address is therefore easy to compute: write a 0 after the segment, write the EA right-aligned beneath it, and add the two numbers.

4.1.3.2Step by step: with BP

If BP is in the address, the same calculation is done with the SS segment. The second example in the slides reads a word and uses a negative displacement:

MOV AX, [BP + DI - 2]   ; SS = 2000h, BP = 0100h, DI = 0010h
  1. Take the base register BP = 0100h.
  2. Add the index register DI = 0010h: 0110h.
  3. The displacement is −2; it sits in the machine code as the byte FE and becomes FFFEh by sign extension.
  4. EA = 0100h + 0010h + FFFEh = 1 010Eh → 010Eh. The overflowing bit is discarded; the result is the same as 0110h − 2.
  5. Because BP is used, the segment is SS: 20000h + 010Eh = 2010Eh. Since AX is a word, two bytes are read: AL ← [2010Eh], AH ← [2010Fh].
BP0100+ DI0010+ d8FFFEEA010EPhysical addressSS × 10h = 20000h+ EA = 010Eh2010EhAX ← [2010Eh], [2010Fh]
Figure 4.1.5: MOV AX, [BP + DI - 2]: EA = 010Eh; because BP is used, the segment is SS and the physical address 2010Eh. The second byte of the word is at 2010Fh.

The machine code of this instruction is 8B 43 FE. The ModR/M byte 43 = 01 000 011: MOD = 01 (d8 present), REG = 000 (AX), R/M = 011 ([BP+DI]). “SS” is not written anywhere in the instruction. The segment choice comes from the R/M field itself: if the R/M value is a combination that contains BP, the hardware selects SS, otherwise DS.

Reading a word has a subtlety on the data-bus side. The 8086's data bus is 16 bits, but memory is addressed byte by byte. The two bytes of a word at an even address arrive together in a single bus cycle. Since 2010Eh in this example is even, the read is a single cycle. Had the word started at an odd address, for example at 2010Fh, the processor would first have read the low byte from the high half of the bus and then, in a separate cycle, the high byte from the low half of the bus. The result is the same, but the access is one bus cycle, that is, at least 4 clock periods, longer. That is why assemblers have the EVEN directive, which aligns word variables to even addresses.

4.1.3.3The effective address calculator

The calculator in the slides performs the same calculation interactively. From the base column you choose BX, BP, or none; from the index column SI, DI, or none; and you enter a displacement. Register and segment values can be written in hexadecimal, and the displacement in decimal (−2) or hexadecimal (1Ah). For a valid combination the tool gives the EA, the default segment, and the physical address. It is suitable for checking a calculation done by hand. On paper the same calculation rests on three rules: do the addition in 16 bits, choose SS if BP is present, and multiply the segment by 10h.

Example 4.1.2

DS = 3000h, SS = 4000h, BX = 0010h, BP = FFFEh, SI = 0005h. What are the effective and physical addresses of the operands [BX+SI+20h] and [BP+4]?

The first operand has no BP. EA = 0010h + 0005h + 0020h = 0035h, segment DS: 30000h + 0035h = 30035h.

For the second operand, EA = FFFEh + 0004h = 1 0002h. The 17th bit is discarded and EA = 0002h. Since BP is present, the segment is SS: 40000h + 0002h = 40002h. Without the wraparound the address would have come out as 50002h. This value is outside the SS segment, and the 8086 does not produce such an address.

4.1.3.4Choosing a mode by data structure

The same byte can be reached with more than one mode. To choose the right mode, look at which part of the data is fixed at assembly time and which part varies at run time. The fixed part goes into the displacement and the varying parts into registers. Table 4.1.6 summarizes the common cases.

Table 4.1.6: The suitable addressing mode by the data accessed.
Data accessedSuitable modeExample
A single variabledirectMOV AX, counter
The element a pointer points toregister indirectMOV AL, [SI]
The i-th element of an array (array fixed, index variable)indexed + d16MOV AL, arr[SI]
A field of a record (structure)based + d8MOV AX, [BX+2]
A matrix or an array of recordsbase + index + dMOV AL, mat[BX+SI]
A parameter or local variable on the stackbased, with BP (SS)MOV AX, [BP+4]
A buffer in another segmentwith a segment overrideMOV AL, ES:[DI]

The idea behind the table is this. The base register shows which record or which row is being worked on. When the record changes, only the base register is updated. The index register counts the element inside the record and is incremented in a loop. The displacement is the fixed location of the array or field; the assembler embeds it in the instruction. For example, in an array of student records of 6 bytes each, the grade field at the 4th byte of a record is read with [BX+4]. To move to the next record, ADD BX, 6 is enough; the read instruction stays the same.

The stack row has a separate importance. When a parameter is passed to a subroutine on the stack, the subroutine copies SP to BP and reaches the parameters with fixed offsets such as [BP+4] and [BP+6]. BP's default segment being SS was chosen for this use: the stack is in the SS segment.

4.1.3.5Code trace: accessing a matrix element

The clearest use of the base + index + displacement mode is a two-dimensional array. In the program below, mat is a byte matrix of 3 rows and 4 columns. The element values were chosen so that they are recognizable at a glance: the first hexadecimal digit of the value is the row number and the second the column number, counting from 1. For example, 32h is the second element of the third row. Since the program counts rows and columns from 0, this element is called mat[2][1].

org 100h
mov bx, 2*4          ; row 2
mov si, 1            ; column 1
mov al, mat[bx+si]   ; mat[2][1]
mov si, 3            ; column 3
mov ah, mat[bx+si]   ; mat[2][3]
sub bx, 4            ; row 1
mov dl, mat[bx+si]   ; mat[1][3]
ret
mat db 11h,12h,13h,14h
    db 21h,22h,23h,24h
    db 31h,32h,33h,34h

The matrix is stored in memory in row-major order: first the four bytes of row 0, then those of row 1, and finally those of row 2. mat starts at 0119h and ends at 0124h. The address of an element is found with this formula:

address(mat[row][column]) = mat + row × number of columns + column

In the program the term row × number of columns is put in BX, the term column in SI, and the relative location of mat in the displacement. The notation mat[bx+si] is the same as [bx+si+0119h] and is encoded as 8A 80 19 01. Since 0119h is greater than 127, d16 is used.

Table 4.1.7: Trace of the matrix access (mat = 0119h, row length 4 bytes).
StepInstructionBXSIEAAXDL
1mov bx, 2*40008h0000h—0000h00h
2mov si, 10008h0001h—0000h00h
3mov al, mat[bx+si]0008h0001h0122h0032h00h
4mov si, 30008h0003h—0032h00h
5mov ah, mat[bx+si]0008h0003h0124h3432h00h
6sub bx, 40004h0003h—3432h00h
7mov dl, mat[bx+si]0004h0003h0120h3432h24h

In step 1, BX = 2 × 4 = 8. The assembler does the multiplication at assembly time and writes 0008h into the instruction. Row 2 is 8 bytes past the start of the matrix. In step 2, SI = 1 selects the column. In step 3, EA = 0119h + 8 + 1 = 0122h and AL = 32h is read. This is column 1 of row 2 of the matrix (both counted from 0).

Steps 4 and 5 stay in the same row and change the column. Since BX is left untouched, the row is fixed. EA = 0119h + 8 + 3 = 0124h and AH = 34h; AX = 3432h. The read instruction is the same as before; only the value of the index register has changed. The sub bx, 4 in step 6 goes up one row: BX = 0004h. Since SI = 3 is kept, the column stays the same. In step 7, EA = 0119h + 4 + 3 = 0120h and DL = 24h. This is column 3 of row 1.

mat (4 bytes per row)column 0123row 0 · 011911121314row 1 · 011D21222324row 2 · 012131323334BX0008SI0001AH00AL32DL00EA = 0119 + 0008 + 0001= 0122h
Figure 4.1.6: Step 3 of the matrix access: BX selects the row (8 bytes ahead) and SI the column (1); EA = 0122h and AL = 32h.

Unlike MOV, sub bx, 4 changes the flags. The result 8 − 4 = 4 is not zero and needs no borrow; ZF = 0, CF = 0, SF = 0. Since 4 = 0000 0100b has an odd number of 1 bits, the parity flag PF = 0. At the end of the program AX = 3432h, BX = 0004h, DL = 24h. Three different elements were read with a single addressing pattern.

In a matrix of words, both terms in the formula are multiplied by 2: address = mat + (row × number of columns + column) × 2. A word occupies 2 bytes, and index registers always count bytes.

4.1.3.6Effective address calculation time

On the 8086 the effective address is computed by a separate addition inside the EU. On the 80286 and later processors there is a separate address unit for this job. On the 8086 the time of the EA calculation is added to the instruction's own time and varies with the mode. Table 4.1.8 gives the EA timing table from the Intel 8086 user's manual.

Table 4.1.8: Time of the effective address calculation on the 8086 (clock periods).
Effective address combinationSaat turu
[BX], [BP], [SI], [DI]5
direct [d16]6
[BP+DI], [BX+SI]7
[BP+SI], [BX+DI]8
single register + d8/d169
[BP+DI+d], [BX+SI+d]11
[BP+SI+d], [BX+DI+d]12
segment prefix+2

The general MOV that moves from memory to a register takes 8 periods plus the EA time. Register-to-register MOV takes 2 periods. Accordingly:

  • MOV AX, BX: 2 periods. Memory is not visited.
  • MOV CL, [BX]: 8 + 5 = 13 periods.
  • MOV CL, [BX+DI+4]: 8 + 12 = 20 periods.
  • MOV CL, ES:[BX]: 8 + 5 + 2 = 15 periods.

An odd detail in the table stands out: [BX+SI] takes 7 periods and [BX+DI] 8. This difference comes from the 8086's internal organization and can be a small selection criterion for the programmer. A word starting at an odd address needs a second bus cycle and so adds 4 more periods per transfer. On a 5 MHz 8086 one clock period is 200 ns. MOV CL, [BX+DI+4] thus takes 20 × 200 ns = 4 µs; the same job register-to-register takes 0.4 µs.

These differences explain why keeping a frequently read value in a register throughout a loop is fast. On each iteration memory is not visited, and the EA calculation disappears entirely. The short direct-address form specific to AL and AX (A0/A1) is also fast: it contains no EA calculation and takes 10 periods. MOV CL, [1234h], on the other hand, takes 8 + 6 = 14 periods.

4.1.4Segment and offset

4.1.4.1From segment:offset to the physical address

The 8086's address bus has 20 lines: A19–A0. With 20 bits, 220 = 1,048,576 different bytes, that is, 1 MB, can be addressed. The processor's registers, however, are 16 bits, and a single register can span only a 64 KB area. The designers solved this mismatch by combining two 16-bit numbers. The first number says which block of memory is used, and the second the position within that block.

Definition 4.1.4

The value in a segment register (CS, DS, SS, ES) is called the segment. An address that comes from the effective address calculation or from a register such as IP or SP is called the offset. An address is written in the form segment:offset. The physical address is found with

physical address = segment × 10h + offset

The segment points to a block of memory starting on a 16-byte boundary, and the offset to the byte within that block.

In the example in the slides, DS = 1234h and SI = 7890h. The address is written 1234:7890. The calculation is done in four steps (Figure 4.1.7):

  1. Take the segment and the offset: 1234h and 7890h.
  2. Multiply the segment by 10h, that is, shift it left 4 bits: 12340h. In hexadecimal notation this is appending a 0 on the right.
  3. Right-align the offset to enter the addition: 07890h.
  4. Add the two numbers: 12340h + 07890h = 19BD0h.
DS1234× 10h12340+ SI7890=19BD0carry: 4 + 9 = D, 3 + 8 = B,2 + 7 = 9, 1 + 0 = 1 → 19BD0h
Figure 4.1.7: The physical equivalent of address 1234:7890: the segment is shifted left 4 bits (12340h), the offset (7890h) is added; the result is 19BD0h.

Adding digit by digit gives 0 + 0 = 0, 4 + 9 = 13 = Dh, 3 + 8 = 11 = Bh, 2 + 7 = 9, 1 + 0 = 1. Since no digit produces a carry, the result is easy to read. An example with carries is the pair 1A5D:FFF3. In the calculation 1A5D0h + 0FFF3h, start from the right: 0 + 3 = 3; D + F = 13 + 15 = 28 = 1Ch, write C in the digit and carry 1; 5 + F + 1 = 21 = 15h, write 5 in the digit; A + F + 1 = 26 = 1Ah, write A in the digit; 1 + 0 + 1 = 2. The result is 2A5C3h. In hexadecimal addition, if a digit exceeds 15, 16 is subtracted and a carry of 1 is passed to the next digit.

In hardware this addition is done by a separate 20-bit adder inside the BIU. The 16 bits of the segment register are fed to the upper 16 inputs of the adder, with 0 wired to the lowest 4 inputs. This wiring is the entire circuit for “multiplying by 10h”; there is no separate multiplier. The adder's output goes to the address latches and from there to the lines A19–A0. When fetching instructions, the BIU uses the same adder with CS and IP.

One consequence of multiplying the segment by 16 is that segments can begin only at addresses that are multiples of 16. This 16-byte unit is called a paragraph. The number in a segment register says at which paragraph the segment starts. Since a segment's offset is 16 bits, a segment is at most 216 = 64 KB long. Because two consecutive segment values start only 16 bytes apart, segments overlap one another. The same physical byte can be reached with many different segment:offset pairs. For example, the pairs 0700:0100, 0710:0000, and 06F0:0200 all point to address 07100h.

What happens if the sum overflows 20 bits? The sum of the pair FFFF:0010 is FFFF0h + 0010h = 100000h; 21 bits are needed. The 8086 has no 21st line, and the overflowing bit is discarded. The address wraps around to 00000h, the start of memory. Addresses from FFFF:0010 to FFFF:FFFF thus fall in the region 00000h–0FFEFh.

4.1.4.2Address lines and memory capacity

The relationship between the number of address lines and the memory size is familiar from decoders in digital design. n address lines produce 2n different binary patterns, and each pattern selects one memory location. How many bits a location holds is determined by the number of data lines:

capacity = 2n × data width

The 8086's 20 address lines select 220 = 1,048,576 locations. Since each location is a byte, the capacity is 1 MB and addresses range from 00000h to FFFFFh. The limit of a segment comes from the offset: 16 bits → 216 = 65,536 bytes = 64 KB. Table 4.1.9 gives the capacity for different numbers of lines.

Table 4.1.9: Memory capacity by the number of address and data lines.
Address / data linesNumber of locationsCapacity
12 / 8212 = 40964096 × 1 B = 4 KB
16 / 4216 = 64 K64 K × 4 bit = 256 Kbit = 32 KB
16 / 864 K64 KB (one segment)
20 / 81 M1 MB (8086)
24 / 1616 M16 M × 2 B = 32 MB
32 / 84 G4 GB (80386)

In a memory chip the number of data lines is the chip's word width. If the capacity is wanted in bytes, the total number of bits is divided by 8. A chip with 16 address lines and 4 data lines holds 65,536 × 4 = 262,144 bits, that is, 32,768 bytes. In an 8086 system, chips of this kind are connected side by side to build an 8- or 16-bit data bus.

The question can also be asked the other way around: how many address lines are needed at minimum for a given capacity? For this, find the first power of 2 equal to or greater than the capacity. If memory is byte-addressed, 232 = 4 GB is not enough for 6 GB; 233 = 8 GB suffices and 33 lines are needed. For 4 KB, 212 = 4096 is exactly enough; 12 lines are needed (A0–A11).

Common mistake

Confusing bits with bytes. A chip with 20 address lines and 16 data lines holds 220 × 16 bits = 16 Mbit. That is 2 MB, not 16 MB. When writing a capacity, it must be stated clearly whether the unit is bits or bytes. The 8086's memory is byte-addressed; there, 20 lines mean 1 MB.

4.1.4.3The reverse calculation: from the physical address to segment:offset

When a physical address is given and the segment and offset are wanted, there is no single answer. Because segments overlap, many pairs give the same address. The right question is the range of values the segment register can take. In the example in the slides, address 2A5C3h is to be accessed with DS:SI.

The largest DS. This is the case where SI is smallest. DS × 10h must not exceed 2A5C3h. Taking the first four hexadecimal digits of the address gives DS = 2A5Ch. DS × 10h = 2A5C0h, leaving SI = 2A5C3h − 2A5C0h = 0003h. Had DS been 2A5Dh, 2A5D0h would already have been greater than 2A5C3h.

The smallest DS. This is the case where SI is largest. SI can be at most FFFFh. In this case DS × 10h ≥ 2A5C3h − FFFFh = 1A5C4h must hold. Dividing 1A5C4h by 10h gives 1A5C.4h. Since DS is an integer, it is rounded up: DS = 1A5Dh. Then SI = 2A5C3h − 1A5D0h = FFF3h.

How many pairs? Each time DS increases by one, the start of the segment moves ahead by 10h and, for the same address, SI decreases by 10h. DS can take any value from 1A5Dh to 2A5Ch. The number of pairs is 2A5Ch − 1A5Dh + 1 = 0FFFh + 1 = 1000h = 4096.

4096 valid DS valuesDS = 1A5DhDS = 2A5ChSI = FFF3hSI = 0003hleft: SI would exceed FFFFhright: SI would be < 0
Figure 4.1.8: The values DS can take for address 2A5C3h: smallest 1A5Dh (SI = FFF3h), largest 2A5Ch (SI = 0003h); there are 4096 pairs in the range.

Such a calculation is always checked in the forward direction. 1A5Dh × 10h + FFF3h = 1A5D0h + FFF3h = 2A5C3h. 2A5Ch × 10h + 0003h = 2A5C0h + 3 = 2A5C3h. Both ends give the same physical address.

The length of the range is not the same for every address. For very small addresses, the lower bound of DS runs against 0. For example, for address 00345h, DS is at least 0000h and at most 0034h, and there are only 35h = 53 pairs. For addresses of 0FFF0h and above, the range is always 4096 pairs. This count does not take the wraparound at the 1 MB boundary into account; wrapped pairs such as FFFF:0355 also go to 00345h.

4.1.4.4The segment override prefix

The default segment rule chooses the right segment in most cases. Sometimes, however, a program wants to reach a byte outside the data segment. For this, the name of a segment register and a colon are written in front of the square brackets. This notation is called a segment override prefix.

MOV AX, 0B800h
MOV ES, AX          ; ES = video memory
MOV BX, 0
MOV AL, ES:[BX]     ; read ES:0000
MOV AL, [BX]        ; read DS:0000
MOV DL, SS:[SI]     ; read SS:SI

In machine code the prefix is a one-byte code placed in front of the instruction: ES: = 26h, CS: = 2Eh, SS: = 36h, DS: = 3Eh. When the processor reads this byte, it changes the default segment only for the instruction that follows. The prefix does not carry over to the next instruction. MOV AL, ES:[BX] thus becomes 26 8A 07: a 26 has been added in front of the code 8A 07 of the unprefixed MOV AL, [BX]. 2 clock periods are also added to the EA calculation.

A prefix is needed in three cases:

  • To access data in another segment without changing DS. Video memory is the most frequent example.
  • To access data on the stack with a register other than BP: SS:[BX].
  • To access a table in the code segment: CS:[SI]. Some programs place constant tables next to the code; even if DS points elsewhere, the table is read with CS.

Not every prefix can change every access. IP is always used with CS and SP always with SS; these pairings are wired into the hardware. Instruction fetch is done from CS:IP and stack operations (PUSH, POP, CALL, RET) from SS:SP. ES:DI, the destination of string instructions, cannot be changed either. The string source DS:SI, on the other hand, can be redirected to another segment with a prefix.

Definition 4.1.5

The default segment is the segment used in a memory access when there is no prefix. It is CS for instruction fetch (with IP), SS for stack operations (with SP), SS for addresses containing BP, ES for the string destination (with DI), and DS for all other data accesses. A segment prefix changes the default segment of data accesses only for that instruction.

4.1.4.5Code trace: video memory with ES

On IBM PC-compatible computers the contents of the color text screen sit in the memory starting at physical address B8000h. The display card reflects every byte written to this memory onto the screen at once. Each character cell of the screen is two bytes: first the character's ASCII code, then the attribute byte that determines the color. A row is 80 cells, that is, 160 bytes. The program below uses ES to write a yellow K into the first cell of row 1 of the screen and also reads the same offset with DS.

ORG 100h
MOV AX, 0B800h
MOV ES, AX         ; ES = video
MOV BX, 00A0h      ; row 1
MOV BYTE PTR ES:[BX], 'K'
MOV BYTE PTR ES:[BX+1], 1Eh
MOV AL, [BX]       ; DS:00A0h
MOV DL, ES:[BX]    ; B800:00A0h
RET
Table 4.1.10: Trace of the segment prefix program (DS = 0700h; the video cell initially holds 20h 07h).
IPInstructionMachine codeAddress accessedResult
0100hMOV AX, 0B800hB8 00 B8—AX = B800h
0103hMOV ES, AX8E C0—ES = B800h, DS = 0700h
0105hMOV BX, 00A0hBB A0 00—BX = 00A0h
0108hMOV BYTE PTR ES:[BX], 'K'26 C6 07 4BB80A0h[B80A0h] = 4Bh
010ChMOV BYTE PTR ES:[BX+1], 1Eh26 C6 47 01 1EB80A1h[B80A1h] = 1Eh
0111hMOV AL, [BX]8A 07070A0hAL = 00h
0113hMOV DL, ES:[BX]26 8A 17B80A0hDL = 4Bh
0116hRETC3stackIP = 0000h

The first two instructions set up ES. On the 8086 a constant cannot be loaded directly into a segment register; B800h is first moved into AX and from there into ES. DS still points to the program's own segment (0700h). This way access to the program's variables is not disturbed. The third instruction puts 00A0h = 160 into BX. This number comes from the calculation (1 × 80 + 0) × 2 and is the offset in video memory of the first cell of row 1 (rows are counted from 0).

The fourth instruction begins with the ES: prefix. The 26 byte in the machine code makes the instruction that follows, C6 07 4B (“set the byte BX points to to 4Bh”), go to the ES segment. The physical address is B8000h + 00A0h = B80A0h, and the ASCII code of the letter 'K', 4Bh, is written there. The fifth instruction writes 1Eh to the next byte. 1Eh = 0001 1110b is the attribute byte: the background color bits (6–4) 001 = blue, the foreground color bits (3–0) 1110 = yellow. A yellow K appears on the screen on a blue background.

The sixth instruction carries no prefix. [BX] uses DS by default and reads address 07000h + 00A0h = 070A0h. This address falls in the 256-byte PSP (program segment prefix) area in front of the COM program; in the example there is 00h there and AL = 00h. The same offset has gone to an entirely different byte with a different segment. The seventh instruction again uses the ES: prefix and reads the 4Bh written to video memory: DL = 4Bh.

DS = 0700h07000h + 00A0h = 070A0h00h+0ES = B800hB8000h + 00A0h = B80A0h4Bh+01Eh+1screen, row 1:KAL00hDL00h
Figure 4.1.9: The same offset (00A0h) in two segments: without a prefix, 070A0h is read through DS (AL = 00h); with the ES: prefix, the 'K' (4Bh) at B80A0h is read.

At the end of the program ES = B800h and DS = 0700h. The prefix affected only the instruction it was written on and never touched DS.

4.1.4.6Code trace: the BP and SS trap

In COM programs CS, DS, SS, and ES carry the same value. Choosing the wrong segment in a COM program therefore often goes unnoticed. In an EXE program with separate segments, however, accessing data through BP fetches the wrong byte. The program below shows this trap.

data segment
pad db 3 dup(0)
x db 'D'
data ends
stk segment stack
dw 64 dup(0)
stk ends
code segment
assume cs:code, ds:data, ss:stk
start:
mov ax, data
mov ds, ax
mov bp, offset x
mov al, [bp]         ; reads SS:BP!
mov bl, ds:[bp]      ; DS:BP
mov si, offset x
mov cl, [si]         ; DS:SI
mov ax, 4C00h
int 21h
code ends
end start

Three segments are defined in the program. The data segment is four bytes: three zero bytes and x, which holds the letter 'D'. The relative location of x is 0003h. The stk segment is a stack of 64 words filled with zeros. The word stack tells the linker that this is the program's stack. When opening the program, the loader sets SS to this segment and SP to its end (0080h). The assume directive generates no code; it tells the assembler which segment register will point to which segment.

The load layout of the program is as follows. DOS places the PSP at paragraph 0700h; the program's image starts 256 bytes later, at 0710h. The segments are laid out in definition order, aligned to paragraph boundaries. The four-byte data takes one paragraph: 0710h. stk starts right after it at 0711h, and the code starts at 0719h after the 128-byte stack. These values are one example layout. On a real DOS the paragraph numbers vary with the occupied part of memory; the logic of the calculation stays the same.

Table 4.1.11: Trace of accessing data through BP (data = 0710h, stk = 0711h; x = 0710:0003 = 07103h).
InstructionMachine codeDSSSAddress accessedResult
mov ax, veriB8 10 070700h0711h—AX = 0710h
mov ds, ax8E D80710h0711h—DS = 0710h
mov bp, offset xBD 03 000710h0711h—BP = 0003h
mov al, [bp]8A 46 000710h0711hSS:0003 = 07113hAL = 00h
mov bl, ds:[bp]3E 8A 5E 000710h0711hDS:0003 = 07103hBL = 44h ('D')
mov si, offset xBE 03 000710h0711h—SI = 0003h
mov cl, [si]8A 0C0710h0711hDS:0003 = 07103hCL = 44h ('D')
mov ax, 4C00h / int 21hB8 00 4C / CD 210710h0711h—return to DOS, code 0

When the program starts, DS does not point to the data segment; the loader sets DS to the PSP (0700h). The instruction mov ax, data loads the paragraph number of the data segment into AX. This number becomes known at load time; the loader writes it into the instruction by consulting the relocation table in the EXE file. After mov ds, ax, DS = 0710h. SS = 0711h is a separate block; in this program DS ≠ SS.

mov bp, offset x puts the correct offset of x (0003h) into BP. The address is right; the problem is in the segment. In mov al, [bp] there is no prefix and BP is in the address. The processor chooses SS and reads address 0711h × 10h + 3 = 07113h. That is the fourth byte of the stack and it holds 00h. AL = 00h; the 'D' has not arrived. The assembler gives no error, because the instruction is valid.

In mov bl, ds:[bp] the DS: prefix changes the default. The byte 3E is added to the front of the machine code and 07103h is read: BL = 44h ('D'). When the same offset is taken into SI, no prefix is needed. [si] uses DS by default and CL = 44h. The last two instructions call DOS's 4Ch service: AH = 4Ch is “terminate the program” and AL = 0 is the return code.

data: DS = 0710h000000000001000002440003phys. 07100h…stack: SS = 0711h000000000001000002000003phys. 07110h…BP0003SI0000AL00BL00CL00SS:0003 → 07113h
Figure 4.1.10: The mov al, [bp] step: BP = 0003h is the correct offset, but because the default segment is SS, the byte at 07113h of the stack is read (AL = 00h). The letter 'D' is at 07103h in the data segment.

The rule from this trace is simple. To access data, choose BX, SI, or DI; to access the stack, choose BP. If accessing the data segment with BP is truly necessary, write the DS: prefix. The detail 46 00 in the machine code of mov al, [bp] is also noteworthy. Since [BP] without a displacement cannot be encoded, the assembler produced [BP+0].

Common mistake

Accessing a variable through BP, getting the right result in a COM program, and then moving the code to an EXE program. In a COM program CS = DS = SS, so [BP] and DS:[BP] go to the same byte and the error is invisible. In an EXE program with separate segments the same code reads from the stack. The error is noticed not at assembly time but when wrong values appear.

4.1.4.7Changing a segment register

The values of segment registers can be changed, but each has its own rules.

PUSH DS            ; save DS
MOV  AX, 0B800h
MOV  DS, AX        ; temporary
MOV  BYTE PTR [0], 'Z'
POP  DS            ; variables back

MOV  AX, new_stack
MOV  SS, AX        ; right after it
MOV  SP, 0400h     ; set SP

DS. Variable names in assembly are only offsets. If the program changes DS, the same name goes to a byte in another segment. The first four lines of the code temporarily set DS to B800h to write a Z in the top left corner of the screen. BYTE PTR [0] thus goes to B8000h. When the job is done, POP DS restores the old value. Had PUSH and POP not been used, all subsequent variable accesses would have gone to video memory. A safer way is to use ES without touching DS at all. ES is the default segment for no access other than the string destination.

SS and SP. The two change together. After SS is changed, SP must take a value that suits the new segment. If an interrupt came between the two instructions, the processor would push the return address to a wrong place formed by the new SS and the old SP. The 8086 prevents this in hardware: after an instruction that does a MOV or POP to a segment register, no interrupt is accepted until the next instruction finishes. That is why MOV SP, … is written right after MOV SS, AX, and the SS:SP pair is never half set.

CS. It cannot be written with MOV. If CS changes, the next instruction is fetched from an entirely different place and the old value of IP becomes meaningless. CS therefore changes together with IP: far JMP, far CALL, far RET, INT, and IRET load both at once. Reads such as MOV AX, CS, on the other hand, are free.

4.1.5Data type and byte order

4.1.5.1byte ptr and word ptr

A memory address points to a single byte. The 8086, however, can read and write a byte (8 bits) or a word (16 bits, two bytes) starting at the same address. Which one an instruction does is written in the lowest bit of the opcode, the W bit: W = 0 means byte and W = 1 means word. This is the difference between the opcodes 8A and 8B. To set this bit correctly, the assembler must know the size of the access.

In most instructions the size can be told from the other operand. In MOV [BX], AL, AL is 8 bits and a byte is written. In MOV [BX], AX, AX is 16 bits and a word is written. But in MOV [BX], 5 neither operand has a size of its own. The square brackets say only an address. The number 5 fits both in a byte (05) and in a word (05 00). The assembler cannot decide in this case. Some assemblers report an error, others guess a size. If the guess is wrong, the program silently corrupts the neighboring byte.

Definition 4.1.6

A data type specifier is the addition that tells the assembler whether a memory operand is a byte or a word. byte ptr [BX] means a one-byte access and word ptr [BX] a two-byte access. emu8086 also recognizes their short forms: b.[SI] for byte, w.[DI] for word.

The specifier is for the assembler only; the processor does not see it. MOV BYTE PTR [BX], 5 is encoded as C6 07 05 (3 bytes) and MOV WORD PTR [BX], 5 as C7 07 05 00 (4 bytes). The whole difference is the opcode's W bit (C6 → C7) and the length of the constant. Figure 4.1.11 shows reading at the same address with two different sizes.

34[BX]12[BX+1]…[BX+2]byte ptr [BX] → 34hword ptr [BX] → 1234h (low byte at the low address)
Figure 4.1.11: At the same address byte ptr reads one byte and word ptr reads two.
Table 4.1.12: Where the access size is known from.
InstructionHow is the size known?
MOV [BX], ALAL is 8 bits → a byte is written
MOV [BX], AXAX is 16 bits → a word is written
MOV [BX], 5ambiguous → MOV BYTE PTR [BX], 5 or MOV WORD PTR [BX], 5
MOV AL, numAL is 8 bits; compatible if num is defined with DB, a type mismatch if with DW

The last row shows that a variable name also carries a type. A variable defined as num DB 7 is of type byte, and one defined with DW is of type word. In an instruction containing a variable name, the assembler takes the size from this type and reports an error if it does not match the register. To change the type deliberately, a specifier is again written: MOV AL, BYTE PTR wvar reads only the low byte of a word variable.

4.1.5.2Code trace: byte ptr and word ptr

The program below writes to and reads from the same address in different sizes. The four bytes starting at 0200h hold the values AA BB CC DD beforehand. That way it is clear which bytes change.

MOV BX, 0200h
MOV WORD PTR [BX], 1234h
MOV BYTE PTR [BX], 0FFh
MOV WORD PTR [BX], 0FFh
MOV AX, [BX]        ; word
MOV CL, [BX+1]      ; byte
Table 4.1.13: Trace of byte ptr and word ptr (initially [0200h…0203h] = AA BB CC DD).
StepInstructionMachine code0200h 0201h 0202h 0203hRegister
1MOV BX, 0200hBB 00 02AA BB CC DDBX = 0200h
2MOV WORD PTR [BX], 1234hC7 07 34 1234 12 CC DD—
3MOV BYTE PTR [BX], 0FFhC6 07 FFFF 12 CC DD—
4MOV WORD PTR [BX], 0FFhC7 07 FF 00FF 00 CC DD—
5MOV AX, [BX]8B 07FF 00 CC DDAX = 00FFh
6MOV CL, [BX+1]8A 4F 01FF 00 CC DDCL = 00h

In step 2 two bytes are written. The low byte of the constant, 34h, goes to the low address (0200h) and the high byte, 12h, to the next address (0201h). In step 3 only 0200h changes and becomes FFh; the 12h at 0201h stays in place. In step 4 the same constant FFh is this time written as a word. FFh as a word means 00FFh. FFh goes to 0200h and 00h to 0201h. The 12h preserved in the previous step is now erased. The constant itself is the same; only the specifier has changed.

In step 5 no specifier is needed; since AX is 16 bits, a word is read. The FFh at 0200h goes to AL and the 00h at 0201h to AH: AX = 00FFh. In step 6, CL is 8 bits and the single byte at [BX+1] = 0201h is read: CL = 00h. The bytes CC DD at 0202h and 0203h are not touched in any step.

BX0200BHBLAX0000AHALCX0000CHCLDS:0200 … DS:02030200FF0201000202CC0203DD
Figure 4.1.12: Step 4: the 0FFh written with WORD PTR spreads over two bytes (FF 00); the 12h preserved in the previous step is erased.

4.1.5.3Little-endian order

In the previous trace we saw that words sit “reversed” in memory: 1234h was stored in memory as 34 12. This is not a coincidence but the 8086's byte-order rule.

Definition 4.1.7

The order that writes the low byte of a multi-byte value to the low address and the high byte to the next address is called little-endian (low byte first). Conversely, the order that writes the high byte first is big-endian. The 8086 and the entire x86 family are little-endian.

AX = 1234h1234high byte (AH)low byte (AL)0200340201120202…low address → low byte
Figure 4.1.13: Little-endian: the low byte 34h of the word 1234h is written to the low address and the high byte 12h to the next address.

The counterpart of the rule at the register level is very tidy. The instruction MOV [0200h], AX writes AL to 0200h and AH to 0201h. MOV AX, [0200h] does the opposite: the byte at 0200h goes to AL and the one at 0201h to AH. The low half of a register always matches the low address. One benefit of little-endian arises from this. If a byte is read from the address of a word variable, the low byte arrives. A small number such as 0034h gives the same value at the same address whether read as a word or as a byte.

The emu8086 memory window shows bytes in address order. That is why words look reversed in the window: 1234h → 34 12. The rule also applies to constants in machine code. MOV AX, 1234h is encoded as B8 34 12 and MOV AX, 0B800h as B8 00 B8. Addresses obey the same rule: MOV AX, [1000h] = A1 00 10.

Common mistake

Reading a memory dump left to right and assembling the word that way. If 0200h holds 34h and 0201h holds 12h, then after MOV AX, [0200h] AX = 1234h, not 3412h. The low address is the low byte. The same misreading is made when reading machine code: the address in the instruction A1 00 10 is 1000h, not 0010h.

4.1.5.4Code trace: index in a word array

When byte order and byte addressing come together, a common mistake appears. To reach the i-th element of a word array, 2i, not i, must be put in the index register. The program below follows first the wrong and then the right way.

org 100h
mov si, 1            ; index 1
mov ax, arr[si]      ; BUG!
shl si, 1            ; index × 2
mov bx, arr[si]      ; arr[1]
mov si, 2            ; index 2
shl si, 1            ; SI = 4
mov cx, arr[si]      ; arr[2]
ret
arr dw 1234h, 5678h, 9ABCh

Adding up the instruction lengths, arr starts at 0117h. The three words are laid out in memory in little-endian as 34 12 78 56 BC 9A between 0117h and 011Ch. arr[0] = 1234h is at 0117h, arr[1] = 5678h at 0119h, and arr[2] = 9ABCh at 011Bh.

Table 4.1.14: Trace of the index in a word array (arr = 0117h: 34 12 78 56 BC 9A).
StepInstructionSIEABytes readResult
1mov si, 10001h———
2mov ax, arr[si]0001h0118h12 78AX = 7812h (wrong)
3shl si, 10002h———
4mov bx, arr[si]0002h0119h78 56BX = 5678h = arr[1]
5mov si, 20002h———
6shl si, 10004h———
7mov cx, arr[si]0004h011BhBC 9ACX = 9ABCh = arr[2]

In step 1 the programmer gives SI = 1 with the thought “the second element.” But an index register counts bytes, not elements. In step 2, EA = 0117h + 1 = 0118h. The word read from there is a combination of the high byte of arr[0] (12h) and the low byte of arr[1] (78h). By the little-endian rule, the 12h at 0118h goes to AL and the 78h at 0119h to AH: AX = 7812h. This value is not any element of the array. The processor gives no warning; reading a word from an odd address is valid on the 8086, it just takes one extra bus cycle.

The shl si, 1 in step 3 shifts SI left by one bit, that is, multiplies by 2: SI = 2. In a word array the byte offset is index × 2. In step 4, EA = 0119h and BX = 5678h = arr[1] arrives correctly. Steps 5 and 6 do the same job for index 2: SI = 2, then 4. In step 7, EA = 011Bh and CX = 9ABCh = arr[2]. Shifting is the shortest and fastest way to multiply by 2; D1 E6 is a two-byte instruction.

34011712011878011956011ABC011B9A011Carr[0]arr[1]arr[2]SI0001AX7812BX0000CX0000EA = 0117 + 0001 = 0118
Figure 4.1.14: With SI = 1, arr[si] reads from the middle of two elements: the 12h at 0118h and the 78h at 0119h combine, AX = 7812h.

Unlike MOV, the shl instruction also updates the flags. Shifting 1 by one bit gives 2; since the bit shifted out is 0, CF = 0, and since the result is nonzero, ZF = 0. The auxiliary carry flag AF is undefined after shift instructions. When walking a word array with a loop, SI is advanced on each iteration with ADD SI, 2. INC SI is only for byte arrays.

4.1.6The MOV instruction

4.1.6.1Definition and rules

MOV, used in all the previous examples, is the 8086's most frequently used instruction. A significant part of the code that compilers produce consists only of MOVs.

Definition 4.1.8

The instruction MOV destination, source copies the value in the source to the destination. The source does not change. The source can be an immediate value (a constant), a general-purpose register, a segment register, or a memory location. The destination is a general-purpose register, a segment register (except CS), or a memory location.

The rules of MOV are gathered in five points:

  1. No value is assigned to CS and IP with MOV. CS can be read as a source; IP does not appear in any MOV.
  2. The two operands must be the same size: both bytes or both words.
  3. The two operands cannot both be memory.
  4. An immediate value cannot be loaded into a segment register, and one segment register cannot be copied directly to another.
  5. MOV does not affect the flags.
REGSREGMEMIMM✗MEM ↔ MEM ✗SREG ↔ MEMREG → REG
Figure 4.1.15: The allowed source → destination directions for MOV. There is no arrow between memory and memory, between a constant and a segment register, or between two segment registers.

Most of the rules come from the structure of the machine code. A MOV instruction contains at most one ModR/M byte, and this byte can define only one memory operand. The second operand is a register in the REG field or a constant at the end of the instruction. There is no room for two memory operands. Segment registers have separate opcodes: 8E moves to a segment register and 8C from one. Their second operand is always a general register or a memory word selected by ModR/M. That is why there is no instruction from segment to segment or from a constant to a segment.

That the flags do not change is also a deliberate choice. After a comparison, a value may need to be brought into a register before the conditional jump. If MOV disturbed the flags, the result of the comparison would be lost.

The two examples in the slides apply the rules. MOV AX, BX copies the value in BX to AX; BX does not change. MOV [SI], 10h, on the other hand, wants to write 10h to the address DS:SI that SI points to. The destination is a memory location, the source is a constant, and the size is ambiguous. The correct notation is MOV BYTE PTR [SI], 10h.

4.1.6.2Supported operands

The emu8086 documentation lists the valid forms of MOV in two groups. Table 4.1.15 gives this list along with the meanings of the abbreviations used in the notation.

Table 4.1.15: Supported operand combinations of the MOV instruction.
General-purposeWith segment registers
MOV REG, memoryMOV SREG, memory
MOV memory, REGMOV memory, SREG
MOV REG, REGMOV REG, SREG
MOV memory, immediateMOV SREG, REG
MOV REG, immediate—
  • REG: AX, BX, CX, DX, AH, AL, BL, BH, CH, CL, DH, DL, DI, SI, BP, SP.
  • SREG: DS, ES, SS, and CS. CS can be only the second operand, that is, the source.
  • memory: [BX], [BX+SI+7], a variable name, and any of the 24 forms.
  • immediate: constants such as 5, −24, 3Fh, 10001101b.

The forms MOV SREG, immediate and MOV SREG, SREG do not exist. The value is first taken into a general register: MOV AX, 0B800h followed by MOV DS, AX. There are two ways to copy from segment to segment: MOV AX, ES / MOV DS, AX or PUSH ES / POP DS. The second way does not disturb a general register but uses the stack.

4.1.6.3Valid or not?

The rules can be tested on ten instructions. Table 4.1.16 gives the status and reason for each instruction. The assembler reports an error for every invalid instruction.

Table 4.1.16: Validity of ten MOV instructions.
No.InstructionStatusReason and correct form
1MOV [BX], [SI]invalidthere is no memory-to-memory MOV → MOV AL, [SI] · MOV [BX], AL
2MOV DS, ESinvalidthere is no segment-to-segment → MOV AX, ES · MOV DS, AX or PUSH ES · POP DS
3MOV DS, 100hinvalida constant cannot be assigned to a segment
4MOV CS, AXinvalidCS cannot be the destination (use a far JMP); IP cannot be written either (JMP AX instead of MOV IP, AX)
5MOV [BX], 5invalidthe size is ambiguous → BYTE PTR / WORD PTR
6MOV AX, CSvalidCS can be a source; its code is 8C C8
7MOV SP, BXvalidSP is a general register; but this moves the stack somewhere else
8MOV BL, DXinvalid8 and 16 bits do not match
9MOV AL, [SI+BP]validsame as [BP+SI]; segment SS
10MOV 5, AXinvalidthe destination cannot be a constant

Instruction 7 deserves some attention. The instruction obeys the rules and the assembler accepts it. But the moment SP's value changes, the location of the stack changes too. The next PUSH, CALL, or incoming interrupt writes its data to where BX points. If this line was not written on purpose, the program often returns to a wrong address at RET. Instruction 9 is a reminder that the writing order does not matter: [SI+BP] goes to the SS segment because it contains BP.

4.1.6.4Code trace: block copy through a register

Since there is no memory-to-memory MOV, to copy a block of memory elsewhere every byte is passed through a register. The program below copies the four-byte string src into the buffer dst.

org 100h
mov si, offset src
mov di, offset dst
mov cx, 4
copy:
mov al, [si]         ; memory → AL
mov [di], al         ; AL → memory
inc si
inc di
loop copy
ret
src db 'ABCD'
dst  db 4 dup('.')

The code is 18 bytes in 0100h–0111h. src starts at 0112h and dst at 0116h. 4 dup('.') reserves four period characters (2Eh). The instruction loop copy decrements CX by one and jumps to the label copy if CX is not zero. The machine code is E2 F8: LOOP is at 010Fh, the next instruction is at 0111h, and 0111h + (−8) = 0109h, which is the address of copy. The jump is in relative mode.

Table 4.1.17: Trace of the block copy (src = 0112h: 'ABCD', dst = 0116h: '....').
StepInstructionSIDICXALdst
1mov si, offset src0112h0000h0000h00h....
2mov di, offset dst0112h0116h0000h00h....
3mov cx, 40112h0116h0004h00h....
4mov al, [si]0112h0116h0004h41h....
5mov [di], al0112h0116h0004h41hA...
6inc si0113h0116h0004h41hA...
7inc di0113h0117h0004h41hA...
8loop copy0113h0117h0003h41hA...
9–13iteration 20114h0118h0002h42hAB..
14–18iteration 30115h0119h0001h43hABC.
19–23iteration 40116h011Ah0000h44hABCD
24ret0116h011Ah0000h44hABCD

The first three steps set up the two pointers and the counter. SI holds the offset of the source and DI that of the destination; the two pointers point to two separate buffers. CX = 4 is the number of bytes to copy. In step 4, mov al, [si] moves from memory to a register and AL = 'A' = 41h. In step 5, mov [di], al moves from the register to memory and 41h is written to 0116h. AL is a way station here. Since there is no memory-to-memory MOV, there is no other way.

In steps 6 and 7 the two pointers advance by one byte together. In step 8, LOOP lowers CX to 3. Since CX is not zero, IP = 0109h and the loop returns to the start. The second, third, and fourth iterations repeat the same five steps; the table summarizes each iteration in a single row. At the end of the fourth iteration CX = 0 and LOOP does not jump; the program falls through to ret. The destination now contains “ABCD.” SI and DI point right past the buffers: SI = 0116h, DI = 011Ah. The final value of SI happens to be the start of dst, because the two buffers are adjacent.

source'A'0112'B'0113'C'0114'D'0115dst'A'0116'.'0117'.'0118'.'0119SIDIAL'A'CX0004
Figure 4.1.16: Step 5 of the block copy: the 'A' (41h) in AL is written to 0116h, which DI points to.

MOV does not change the flags, but INC does. The flag state influences no decision in this program. LOOP does not look at the flags; it looks only at CX. Still, the trace shows the parity flag changing with the INCs. For example, when DI = 0117h after inc di, the low byte is 17h = 0001 0111b. Since it has four 1 bits, PF = 1.

Each byte needs two memory accesses, two pointer increments, and one loop instruction. Because this job is done so often, the 8086 has a separate instruction for it: REP MOVSB copies CX bytes from DS:SI to ES:DI and advances the pointers itself. The same program shrinks with string instructions to the lines CLD, REP MOVSB.

4.1.7Example program: printing an 'A' on the screen

4.1.7.1The program and its machine code

What has been described so far comes together in a small program. The program writes a character directly into the video memory of the color text screen. No service of the operating system is used; writing to the screen amounts to putting a word at a particular memory address.

ORG 100h          ; for a .com program
MOV AX, 0B800h    ; AX = B800h
MOV DS, AX        ; DS = B800h
MOV CL, 'A'       ; CL = 41h
MOV CH, 11011111b ; CH = DFh
MOV BX, 15Eh      ; BX = 015Eh
MOV [BX], CX      ; B800:015E ← CX
RET               ; back to DOS

Each line of the program introduces an element. ORG is a directive; it determines the program's start address and is not translated into machine code. Everything after the semicolon is a comment; the assembler ignores it. MOV copies a value between source and destination. Since a constant cannot be assigned directly to DS, B800h is first loaded into AX. 'A' is a character constant and is the same as the ASCII code 41h. 11011111b is a constant written in binary and equals DFh. MOV [BX], CX writes the word in CX to the address DS:BX.

Table 4.1.18: Machine code of the program (15 bytes starting at 0100h).
AddressInstructionMachine codeExplanation
0100hMOV AX, 0B800hB8 00 B8B8 = “immediate word into AX”; constant little-endian
0103hMOV DS, AX8E D88E = to a segment register; D8 = 11 011 000 (DS ← AX)
0105hMOV CL, 'A'B1 41B0 + 1 (CL); 41h = 'A'
0107hMOV CH, 11011111bB5 DFB0 + 5 (CH)
0109hMOV BX, 15EhBB 5E 01B8 + 3 (BX)
010ChMOV [BX], CX89 0F89 = word from register to memory; 0F = 00 001 111
010EhRETC3near return

A regular structure stands out in the codes in the table. The opcode of the MOV that loads an immediate value into a register starts at B0 for byte registers and at B8 for word registers, and the register's three-bit number is added. The numbers are AL/AX = 0, CL/CX = 1, DL/DX = 2, BL/BX = 3, AH/SP = 4, CH/BP = 5, DH/SI = 6, BH/DI = 7. B1 for CL, B5 for CH, and BB for BX are found this way. These instructions have no ModR/M byte; the register is embedded in the opcode.

4.1.7.2Code trace

The program runs in emu8086 as a COM program. Initially CS = DS = ES = SS = 0700h, IP = 0100h, and SP = FFFEh. All the cells of the screen are empty: every cell holds the bytes 20h (space) and 07h (gray text on a black background).

Table 4.1.19: Trace of the program that prints 'A' on the screen.
StepInstructionAXDSCXBX[B800:015E] [015F]
0(initial)0000h0700h0000h0000h20h 07h
1MOV AX, 0B800hB800h0700h0000h0000h20h 07h
2MOV DS, AXB800hB800h0000h0000h20h 07h
3MOV CL, 'A'B800hB800h0041h0000h20h 07h
4MOV CH, 11011111bB800hB800hDF41h0000h20h 07h
5MOV BX, 15EhB800hB800hDF41h015Eh20h 07h
6MOV [BX], CXB800hB800hDF41h015Eh41h DFh
7RETB800hB800hDF41h015Eh41h DFh

In step 1, AX = B800h. B800h is the segment of the color text screen; physically it starts at B8000h. In step 2, DS = B800h. From now on, all unprefixed data accesses made with square brackets go to video memory. After this point the program cannot access its own variables through DS; since this small program has no variables, this causes no problem.

Steps 3 and 4 fill the two halves of CX separately. CL = 41h is the character's ASCII code and CH = DFh is the color (attribute) byte. Read together, the two halves give CX = DF41h. In step 5, BX = 015Eh = 350. This number is the relative address in video memory of the position on the screen.

Step 6 is the real work of the program. MOV [BX], CX writes a word. By the little-endian rule, CL (41h) goes to the low address, B800:015Eh, and CH (DFh) to the high address, B800:015Fh. The physical addresses are B8000h + 015Eh = B815Eh and B815Fh. The character byte coming first and the color byte second fits the layout of video memory exactly. That is why the character was put in the low half and the color in the high half. The display card reads these two bytes on the next scan, and a colored 'A' appears in the cell.

AXB800AHALCXDF41CHCLBX015EBHBLDSB800B800:015C … 015F (video memory)015C20015D07015E41015FDF
Figure 4.1.17: Step 6: CX = DF41h is written as a word; [015Eh] = 41h ('A'), [015Fh] = DFh (color). Physical address B815Eh.

In step 7, RET takes the 0000h at the top of the stack into IP and SP = 0000h. The INT 20h at 0700:0000 ends the program. The letter stays on the screen, because video memory is independent of the program. DS remaining B800h causes no problem either; after the program ends, DOS sets up its own registers again.

4.1.7.3Text-mode video memory

In the 80 × 25 text mode the screen consists of 25 rows and 80 columns. Each cell holds 2 bytes in video memory: first the character, then the color. A row is 80 × 2 = 160 bytes and the whole screen takes 25 × 160 = 4000 bytes. If rows and columns are counted from 0, the relative address of a cell is found as follows:

relative address = (row × 80 + column) × 2

The 015Eh in the program comes from this formula: (2 × 80 + 15) × 2 = 175 × 2 = 350 = 15Eh. The letter was written in row 2, column 15 (Figure 4.1.18). The calculation can also be done in reverse. 015Eh = 350 is divided by two: 175. Since 175 = 2 × 80 + 15, it is row 2, column 15.

Acolumn 079024row 2, column 15
Figure 4.1.18: The 80 × 25 text screen. A bright white 'A' on a magenta background has been written into the cell at row 2, column 15.

The bits of the attribute byte encode the color. DFh = 1101 1111b is read as follows:

  • Bit 7 = 1: blinking of the character on a real screen; bright background in emu8086.
  • Bits 6–4 = 101: background color magenta (5).
  • Bits 3–0 = 1111: foreground color bright white (15).

The foreground color selects one of 16 colors with four bits, and the background color one of 8 colors with three bits. The basic colors are 0 black, 1 blue, 2 green, 3 cyan, 4 red, 5 magenta, 6 brown, 7 light gray; 8–15 are their bright versions, and 14 is yellow. The 1Eh in the earlier example thus means yellow text (1110) on a blue background (001), and 07h gray text on a black background.

Example 4.1.3

What would the code look like that writes a yellow 'X' on a green background at row 10, column 40 of the screen? The color byte is 2Eh.

The relative address is (10 × 80 + 40) × 2 = 840 × 2 = 1680 = 690h. The ASCII code of the character 'X' is 58h. Since the character is in the low byte and the color in the high byte, the word to write is 2E58h. 2Eh = 0010 1110b: background 010 (green), foreground 1110 (yellow).

MOV AX, 0B800h
MOV DS, AX
MOV BX, 690h
MOV WORD PTR [BX], 2E58h

WORD PTR is necessary in the last instruction; otherwise the size of the constant stays ambiguous. The code writes 58h to B8690h and 2Eh to B8691h.

4.1.8MOV examples

Each of the short MOV examples in the emu8086 documentation shows a single direction of transfer: memory to register, register to memory, register to register, constant to memory. The sections below trace them in order. All of them are COM programs; initially CS = DS = 0700h and IP = 0100h.

4.1.8.1Memory to register

ORG 100h
MOV AX, [1000h]   ; A1 00 10
RET

Let the bytes CD AB be at DS:1000h beforehand. The instruction reads these two bytes with direct addressing. By the little-endian rule, the CDh at 1000h goes to AL and the ABh at 1001h to AH: AX = ABCDh. The instruction is three bytes; after it executes, IP = 0103h. The physical address is 07000h + 1000h = 08000h. Memory does not change; MOV only copies.

Table 4.1.20: Trace of memory to register (DS:1000h = CD AB).
StepInstructionAXIP (after)[1000h] [1001h]
0(initial)0000h0100hCD AB
1MOV AX, [1000h]ABCDh0103hCD AB
2RETABCDh0000hCD AB

The appearance of this program in the emu8086 window consists of three parts. On the left are the registers; the high and low halves (H, L) of AX, BX, CX, and DX are shown in separate boxes. Initially CS = DS = 0700h, IP = 0100h, SP = FFFEh. In the middle is the memory dump. The physical address 07100h, that is, 0700:0100, holds the three bytes of the instruction (A1 00 10). On the right is the disassembled code: MOV AX, [01000h] followed by RET (C3). The single step button executes one instruction and the registers that changed are highlighted in color. In the real emu8086 the DS:1000h region is initially zero; so in the window AX = 0000h remains after the instruction runs. The value ABCDh is obtained on the assumption that CD AB was written to memory beforehand.

4.1.8.2Register to memory

ORG 100h
MOV BX, 1234h     ; BB 34 12
MOV [2000h], BX   ; 89 1E 00 20
RET
Table 4.1.21: Trace of register to memory (DS:2000h initially 00 00).
StepInstructionBXIP (after)[2000h] [2001h]
0(initial)0000h0100h00 00
1MOV BX, 1234h1234h0103h00 00
2MOV [2000h], BX1234h0107h34 12
3RET1234h0000h34 12

The first instruction loads an immediate value into BX. The second writes BX to a direct address: BL (34h) to 2000h and BH (12h) to 2001h. This instruction is four bytes. Because a register other than AX is used, the short A3 form cannot be chosen. The general opcode 89, a ModR/M byte, and two address bytes are needed. The ModR/M byte 1E = 00 011 110 reads as REG = BX, R/M = direct address. IP advances from 0103h to 0107h. BX does not change. The physical address is 07000h + 2000h = 09000h.

The RET in the last step pulls the COM program's return address (0000h) from the top of the stack. IP after RET is therefore 0000h; the program fetches its next instruction from 0700:0000, that is, from the INT 20h at the start of the PSP. The last step is like this in all COM examples.

4.1.8.3XCHG: swapping

Swapping the places of two values is a basic operation of many algorithms, such as sorting. The 8086 has a separate instruction for it.

Definition 4.1.9

The instruction XCHG destination, source exchanges the contents of the two operands in a single instruction. One operand can be a register and the other a register or memory. Memory with memory, segment registers, and constants cannot be used. The two operands must be the same size. XCHG does not affect the flags.

MOV CX, 10   ; CX = 000Ah
MOV DX, 20   ; DX = 0014h
XCHG CX, DX  ; swap

When numbers carry no suffix, they are taken as decimal. After the first instruction CX = 10 = 000Ah, and after the second DX = 20 = 0014h. After XCHG, CX = 0014h and DX = 000Ah. The flags do not change. The machine code of the instruction is 87 CA: 87 is the word swap, and CA = 11 001 010 means REG = CX, R/M = DX.

Table 4.1.22: Swapping two registers.
StepInstructionCXDX
1MOV CX, 10000Ah0000h
2MOV DX, 20000Ah0014h
3XCHG CX, DX0014h000Ah

4.1.8.4XCHG rules

  • Register ↔ register: XCHG AX, BX.
  • Register ↔ memory: XCHG AL, [SI]. The writing order does not matter; XCHG [SI], AL is the same instruction.
  • There is no memory ↔ memory.
  • Segment registers and constants cannot be used. Swapping with a constant is meaningless anyway: nothing can be written into a constant.
  • The sizes must be the same; the flags do not change.
  • The form XCHG AX, reg has a special one-byte code: 90h + register number. XCHG AX, BX = 93. XCHG AX, AX changes nothing and its code is 90. This byte is also the NOP (no operation) instruction.

Without XCHG, a temporary register would be needed for the swap:

MOV AX, CX    ; AX ← CX (backup)
MOV CX, DX    ; CX ← DX
MOV DX, AX    ; DX ← old CX

This way spends three instructions and one more register. The old value of AX is also lost. XCHG is ahead in time too. On the 8086 register-to-register MOV takes 2 periods and XCHG 4; three MOVs take 6 periods. The one-byte swap with AX takes 3 periods. A swap between a register and memory is expensive: 17 periods plus the EA time. The reason is that the processor first reads from memory and then writes to memory; two separate bus cycles are needed.

The use of XCHG with memory has a special importance in multiprocessor systems. Because the read and the write are done in a single instruction, the chance of another processor accessing the same byte in between is narrowed. When used with the LOCK prefix, the 8086 keeps the LOCK̅ pin active for the duration of the instruction and does not hand the bus to another bus master. The locks that ensure a resource is used by only one processor at a time are built on this mechanism.

4.1.8.5Code trace: swapping with XCHG

The program below shows the use of XCHG with memory, and the same swap done with and without XCHG, side by side.

ORG 100h
MOV SI, OFFSET num
MOV AL, 5Ah
XCHG AL, [SI]      ; AL ↔ [SI]
MOV CX, 1111h
MOV DX, 2222h
MOV AX, CX         ; backup
MOV CX, DX
MOV DX, AX         ; swapped
XCHG CX, DX        ; one instruction
RET
num DB 0A5h
Table 4.1.23: Trace of the swap with XCHG (num = 0116h, initially A5h).
StepInstructionAXCXDXSInum
1MOV SI, OFFSET num0000h0000h0000h0116hA5h
2MOV AL, 5Ah005Ah0000h0000h0116hA5h
3XCHG AL, [SI]00A5h0000h0000h0116h5Ah
4MOV CX, 1111h00A5h1111h0000h0116h5Ah
5MOV DX, 2222h00A5h1111h2222h0116h5Ah
6MOV AX, CX1111h1111h2222h0116h5Ah
7MOV CX, DX1111h2222h2222h0116h5Ah
8MOV DX, AX1111h2222h1111h0116h5Ah
9XCHG CX, DX1111h1111h2222h0116h5Ah

In step 1, SI takes the relative location (0116h) of the variable num. In memory num = A5h. In step 2, AL = 5Ah. The XCHG AL, [SI] (86 04) in step 3 swaps a register with a memory byte: AL = A5h, num = 5Ah. No intermediate register was needed. This single instruction contains both the bus cycle that reads memory and the one that writes to it.

Steps 4 and 5 put recognizable values in CX and DX. Steps 6–8 do the same swap without XCHG. In step 6, a backup of CX is taken into AX; the previous value of AX (00A5h) is lost. In step 7, CX = 2222h. At this moment the old value of CX is held only in AX. In step 8, DX = 1111h and the swap is complete. Three instructions and one register have been spent. The single XCHG CX, DX in step 9 undoes the swap: CX = 1111h, DX = 2222h. AX is not touched in the process.

AX00A5hCX0000hDX0000hnum · 0116h5AhAL ↔ [SI]
Figure 4.1.19: Step 3: XCHG AL, [SI] swaps a register and a memory byte in one instruction; AL = A5h, num = 5Ah.

4.1.8.6Register to register

MOV SI, 3000h  ; SI = address
MOV DI, SI     ; DI = SI
MOV AL, [SI]   ; DS:3000h
MOV [DI+1], AL ; DS:3001h

This example shows what copying between registers that hold addresses means. Let DS:3000h hold 5Ah. The first instruction assigns a relative location (3000h) to SI. The second, MOV DI, SI, makes DI = 3000h. What is copied is the address, not the data in memory. Now two registers point to the same cell. The third instruction reads 5Ah with [SI]: AL = 5Ah. The fourth writes it to [DI+1] = 3001h. In memory, 3000h–3001h is now 5A 5A.

Table 4.1.24: Trace of register to register (DS:3000h = 5Ah).
StepInstructionMachine codeSIDIAL[3000h] [3001h]
1MOV SI, 3000hBE 00 303000h0000h00h5A ??
2MOV DI, SI8B FE3000h3000h00h5A ??
3MOV AL, [SI]8A 043000h3000h5Ah5A ??
4MOV [DI+1], AL88 45 013000h3000h5Ah5A 5A

In C this is like making two pointers equal: q = p; followed by q[1] = p[0];. The pointers themselves are copied, not the data they point to.

4.1.8.7Writing a constant to memory

ORG 100h
MOV BYTE PTR [4000h], 65  ; 'A'
MOV WORD PTR [4002h], 65
RET

Let DS:4000h–4003h initially be 00 99 00 99. The first instruction writes 65 as a single byte. 65 = 41h is the ASCII code of the letter 'A'. The machine code is C6 06 00 40 41 and takes five bytes: the opcode, ModR/M, two address bytes, and one data byte. IP becomes 0105h. 4001h does not change.

The second instruction writes the same constant with WORD PTR. 65 is now the word 0041h; 41h goes to 4002h and 00h to 4003h. The 99h at 4003h is erased. The instruction is six bytes, C7 06 02 40 41 00, and IP advances to 010Bh. The constant has no size of its own; the PTR specifier determines it. The number 65 in the source is the same in both instructions, but it enters the machine code once as one byte and once as two.

Table 4.1.25: Trace of writing a constant to memory (DS:4000h = 00 99 00 99).
StepInstructionIP (after)4000h 4001h 4002h 4003h
0(initial)0100h00 99 00 99
1MOV BYTE PTR [4000h], 650105h41 99 00 99
2MOV WORD PTR [4002h], 65010Bh41 99 41 00
3RET0000h41 99 41 00

4.1.8.8Working with 8-bit halves

Each of AX, BX, CX, and DX has two 8-bit halves that can be used with separate register names: AH and AL, BH and BL, and so on. Writing to one half does not affect the other half. This makes it possible to hold two small values in a single register and to process the bytes of a word separately.

Copying the low byte. In the code below, AL is copied to BL.

MOV AX, 1234h   ; AH = 12h, AL = 34h
MOV BX, 0FFFFh
MOV BL, AL      ; BL only

The first instruction makes AX = 1234h: AH = 12h, AL = 34h. The second fills BX with FFFFh so that the effect can be seen. The third instruction (8A D8) changes only BL: BL = 34h. BH = FFh stays in place and BX = FF34h. Copying from a 16-bit register to an 8-bit register (MOV BL, AX) is invalid; the sizes must be the same.

Adding to the high byte. When arithmetic is done on the halves, the carry is seen not to pass from one half to the other.

MOV AX, 00FFh   ; AH = 00h, AL = FFh
ADD AH, 01h     ; AH only
ADD AL, 01h     ; AL only
MOV AX, 01FFh
ADD AX, 1       ; 16 bits
Table 4.1.26: Adding to the high and low byte (flags: CF, ZF, SF, AF, PF).
StepInstructionMachine codeAXCFZFSFAFPF
1MOV AX, 00FFhB8 FF 0000FFh00000
2ADD AH, 01h80 C4 0101FFh00000
3ADD AL, 01h04 010100h11011
4MOV AX, 01FFhB8 FF 0101FFh11011
5ADD AX, 105 01 000200h00011

In step 2, AH = 00h + 01h = 01h and AX = 01FFh. The result is not zero and there is no carry. Since 01h has an odd number of 1 bits, PF = 0. In step 3, AL = FFh + 01h is computed. The 8-bit result is 00h and a carry comes out as the ninth bit: CF = 1, ZF = 1. A carry also comes out of the low four bits, so AF = 1. There are zero 1s in 00h; zero is an even number and PF = 1. The carry does not pass to AH: AX = 0100h. This is an 8-bit addition and AH is not part of the operation.

In step 4, AX is set to 01FFh again. Because MOV does not change the flags, the flags of the previous step (CF = 1, ZF = 1) remain as they were. In the 16-bit addition of step 5, 01FFh + 1 = 0200h. This time the carry has passed from AL to AH, because the operation is 16 bits. Since no carry comes out of 16 bits, CF = 0. AF is 1 again; F + 1 in the low four bits produces a carry. PF looks only at the low byte of the result: PF = 1 for 00h. The instruction ADD AX, 1 is encoded in the short AX-specific form as 05 01 00.

Common mistake

Thinking the carry of an 8-bit addition passes to the other half of the register. ADD AL, 1 with AL = FFh does not increment AH; it only makes CF = 1. If a 16-bit value is to be added to in 8-bit pieces, ADC (add with carry) is used on the high half: ADD AL, 1 followed by ADC AH, 0.

4.1.8.9Assignment with number bases

In assembly source code, constants can be written in different bases. Whichever base is used, the assembler converts the number to a binary value and writes it into the machine code. The program below uses three bases together.

mov al, 00000101b ; binary
mov bl, 0ah       ; hex
mov cl, 10o       ; octal
add al, bl        ; 5 + 10 = 15
sub al, cl        ; 15 - 8 = 7
Table 4.1.27: Trace of assignment with number bases.
StepInstructionMachine codeALBLCLCFPF
1mov al, 00000101bB0 0505h00h00h00
2mov bl, 0ahB3 0A05h0Ah00h00
3mov cl, 10oB1 0805h0Ah08h00
4add al, bl02 C30Fh0Ah08h01
5sub al, cl2A C107h0Ah08h00

The binary number 00000101b is 5 and AL = 05h. The hexadecimal number 0Ah is 10; a 0 is written in front because it begins with a letter. The octal number 10o is 1 × 8 + 0 = 8 and CL = 08h. In the machine codes the constants are now independent of base: 05, 0A, 08. In step 4, AL = 5 + 10 = 15 = 0Fh. 0000 1111b has four 1 bits; four is even, so PF = 1. In step 5, AL = 15 − 8 = 7 = 07h. Since no borrow is needed, CF = 0 stays. 0000 0111b has three 1s and PF = 0.

4.1.8.10Writing numbers

Table 4.1.28 summarizes the writing rules of constants in assemblers compatible with emu8086 and MASM. The decimal value of all the examples is 25; only 0FFh and the character row differ.

Table 4.1.28: Number bases and their suffixes.
BaseSuffixExampleDecimal value
Decimalnone or d25, 25d25
Binaryb00011001b25
Octalo or q31o25
Hexadecimalh19h, 0FFh25, 255
Character' ''A'65 (41h)

If a hexadecimal number begins with one of the letters A–F, a 0 is put in front: 0Ah, 0B800h. This rule is so that the assembler can tell a number from a name. If Ah is written, it is confused with the register AH, and if B800h is written, with a label or variable name. The assembler assumes that every name begins with a letter and every number with a digit. emu8086 also accepts the C-style form 0x1000. For octal numbers, because the letter o resembles zero, some programmers prefer q.

Example 4.1.4

How is the number 200 written in binary, octal, and hexadecimal? Do MOV AL, 200 and MOV AL, 0C8h produce the same machine code?

Since 200 = 128 + 64 + 8, the binary is 11001000b. With groups of three bits, 11 001 000 = 3 1 0, that is, 310o; with groups of four bits, 1100 1000 = C 8, that is, 0C8h. A 0 is put in front because C is a letter. Both instructions produce B0 C8; the base only changes how the source code reads.

4.1.9Common mistakes

Most errors in memory access do not give an assembly error. The program runs but reads from the wrong address or corrupts the wrong byte. These errors are found in emu8086 by checking the effective address and physical address in the memory window. Table 4.1.29 collects the most frequent ones.

Table 4.1.29: Common mistakes in memory access.
WrongWhat happens?Correct
MOV SI, arrSI is loaded with the value of the first element, not the address of the array.MOV SI, OFFSET arr or LEA SI, arr
INC SI (word array)Reads from the middle of a word; the halves of two elements combine.ADD SI, 2
variable with MOV AL, [BP]Reads from the SS segment; in an EXE program the wrong byte arrives.[BX], [SI], or DS:[BP]
MOV [BX], 5Size is ambiguous; the assembler reports an error or guesses.MOV BYTE PTR [BX], 5
MOV AX, B800hB800h is taken for a label name.MOV AX, 0B800h
Changing DS and leaving itAll the following variable accesses go to another segment.PUSH DS … POP DS, or ES
MOV AX, [0200h] → expecting 3412hLittle-endian was forgotten: if memory has 34 12, AX = 1234h.low address = low byte

The first row depends on the assembler's syntax. In MASM and emu8086, a name defined with data is treated as a variable. The notation MOV SI, arr means the same as MOV SI, [arr] and reads the first word of the array. SI then points to an unrelated place. For the address, the OFFSET operator or the LEA (load effective address) instruction is used. In some assemblers such as NASM, on the other hand, a bare name always means an address and square brackets are required for the contents. This difference must not be overlooked when moving from one source to another.

Common mistake

Forgetting to shift the segment when computing a physical address. For DS = 2000h, BX = 0150h the physical address is 20000h + 0150h = 20150h, not 2000h + 0150h = 2150h. In the reverse mistake the offset is shifted: 2000h + 1500h = 3500h. The segment is always written with a 0 appended on its right, and the offset stays as it is.

Common mistake

Carrying an effective address overflow into 20 bits. With BP = FFFEh, the EA for [BP+4] is 0002h, not 1 0002h. The effective address always wraps in 16 bits; the overflowing bit is not added to the segment value. The segment:offset sum, on the other hand, wraps at 20 bits.

4.1.10Exercises and solutions

The six exercises in the slides are solved here with their intermediate steps.

1. With DS = 3000h, BX = 0010h, SI = 0005h, what are the effective and physical addresses of the operand [BX+SI+20h]?

There is no BP in the address; the segment is DS. EA = 0010h + 0005h + 0020h = 0035h. The physical address is 3000h × 10h + 0035h = 30000h + 0035h = 30035h.

2. With SS = 4000h, BP = FFFEh, what are the effective and physical addresses of the operand [BP+4]?

EA = FFFEh + 0004h = 1 0002h; it wraps in 16 bits and EA = 0002h. Since BP is present, the segment is SS: 40000h + 0002h = 40002h.

3. Which of the notations [BX+BP], [DI+SI], [BX+DI+300], [DX] are valid?

Only [BX+DI+300] is valid: one base, one index, and one d16. [BX+BP] contains two base registers and [DI+SI] two index registers. DX cannot be used in address calculation at all.

4. If [0500h] = 78h and [0501h] = 56h, what is AX after MOV AX, [0500h]? What is AL after MOV AL, [0501h]?

When reading a word, the low address is the low byte: AL = 78h, AH = 56h, AX = 5678h. The second instruction reads only the byte at 0501h: AL = 56h.

5. What does the code look like that writes a yellow 'X' on a green background at row 10, column 40 of the screen? The color byte is 2Eh.

The solution is given in detail in Example 4.1.3. The relative address is (10 × 80 + 40) × 2 = 1680 = 690h; the word to write is 2E58h.

MOV AX, 0B800h
MOV DS, AX
MOV BX, 690h
MOV WORD PTR [BX], 2E58h

6. How is the program that prints 'A' on the screen written with ES without changing DS?

B800h is loaded into ES instead of DS and the ES: prefix is added to the write instruction. DS stays in the program's segment (0700h).

MOV AX, 0B800h
MOV ES, AX
MOV CL, 'A'
MOV CH, 11011111b
MOV BX, 15Eh
MOV ES:[BX], CX      ; 26 89 0F

The machine code of the write instruction is its unprefixed form (89 0F) with 26 added in front. At the end of the program B815Eh = 41h, B815Fh = DFh, and DS = 0700h stays.

4.1.11Summary

  • Addressing: a memory operand has the form [base + index + displacement]. The base is BX or BP, the index SI or DI, and the displacement d8 or d16; each is optional. BX and BP, or SI and DI, cannot be used together. These rules give 24 combinations and are encoded in the MOD and R/M fields of the ModR/M byte.
  • Mode types: the immediate and register modes do not go to memory. The direct, register indirect, based, indexed, and based-indexed modes compute an effective address. String instructions use DS:SI and ES:DI implicitly; I/O instructions go to a separate port space, and jumps to an address relative to IP.
  • The effective address is computed in 16 bits and wraps: with BP = FFFEh, [BP+4] → 0002h. d8 is sign-extended. EA calculation takes 5–12 clock periods on the 8086; a segment prefix adds 2.
  • Segment choice: SS if BP is in the address, otherwise DS. A segment prefix (ES: = 26h, CS: = 2Eh, SS: = 36h, DS: = 3Eh) changes this for a single instruction. CS:IP, SS:SP, and the string destination ES:DI cannot be changed.
  • Physical address = segment × 10h + EA; 1234:7890 → 19BD0h. At most 4096 segment:offset pairs lead to one physical address. n address lines select 2n locations; the 8086's 20 lines give 1 MB, and the 16-bit offset gives the 64 KB segment.
  • Size: byte ptr / word ptr (b. / w. in emu8086) specify the access size; if the other operand is a register, the size is known from it. The 8086 is little-endian: the low byte at the low address. In a word array the byte offset is index × 2.
  • MOV copies and does not affect the flags. There is no MOV from memory to memory, from a constant to a segment register, or from segment to segment; CS and IP cannot be destinations.
  • XCHG swaps two operands in one instruction; segment registers, constants, and two memory operands cannot be used. It does not affect the flags.
  • Video memory is in the B800h segment. Each cell is a character + attribute byte; relative address = (row × 80 + column) × 2.

4.1.12Key terms

  • addressing mode
  • immediate addressing
  • register addressing
  • direct addressing
  • register indirect addressing
  • based / indexed addressing
  • relative addressing
  • base register
  • index register
  • displacement
  • sign extension
  • effective address (EA)
  • ModR/M byte
  • segment
  • offset
  • physical address
  • paragraph (16 bytes)
  • address bus
  • default segment
  • segment override prefix
  • program segment prefix (PSP)
  • .COM program
  • data type specifier
  • byte / word
  • little-endian / big-endian
  • row-major order
  • exchange (XCHG)
  • string
  • I/O port
  • video memory (text mode)
  • attribute byte
  • clock cycle
  • bus cycle

4.1.13Test Yourself

  1. With ES = 5000h and DI = FFF0h, from which physical address does the instruction MOV AL, ES:[DI+20h] read?

    Answer

    EA = FFF0h + 0020h = 1 0010h; it wraps in 16 bits and EA = 0010h. The prefix selects ES: 50000h + 0010h = 50010h. Without the wraparound, 60010h would have been found; this address is outside the ES segment.

  2. How many bytes is the instruction MOV AL, [BP+SI+5] and which segment does it access? What is the ModR/M byte?

    Answer

    The segment is SS, because BP is in the address. Since the displacement 5 is in the range −128…127, d8 is chosen: MOD = 01. REG = 000 (AL), R/M = 010 ([BP+SI]). ModR/M = 01 000 010 = 42h. The instruction is 8A 42 05, that is, 3 bytes.

  3. Starting at DS:0300h, memory holds the bytes 78 56 34 12. What are AX and BL after MOV AX, [0301h] and MOV BL, [0303h]? What happens on the data bus in the first instruction?

    Answer

    AX: the 56h at 0301h goes to AL and the 34h at 0302h to AH; AX = 3456h. BL = 12h. 0301h is an odd address. The 8086 reads a word starting at an odd address with two separate bus cycles; the result is the same, but the access takes 4 clock periods longer.

  4. What is AX when the following program finishes?

    org 100h
    mov bx, offset t
    mov si, 3
    mov al, [bx+si]
    mov ah, [bx+si-2]
    ret
    t db 10h,20h,30h,40h,50h
    Answer

    [bx+si] is byte number 3 of t (counting from 0): AL = 40h. [bx+si-2] is byte number 1: AH = 20h. AX = 2040h. Since the program is 12 bytes long, t is at 010Ch; the result is independent of this address.

  5. Physical address 45678h is to be reached with DS:SI. What are the smallest and largest values DS can take? How many different pairs are there?

    Answer

    Largest DS: the first four digits, 4567h; SI = 45678h − 45670h = 0008h. Smallest DS: DS × 10h ≥ 45678h − FFFFh = 35679h, that is, DS ≥ 3567.9h → 3568h; SI = 45678h − 35680h = FFF8h. The number of pairs is 4567h − 3568h + 1 = 1000h = 4096.

  6. What is the capacity of a memory chip with 18 address lines and 8 data lines? What if it had 18 address lines and 4 data lines?

    Answer

    218 = 262,144 locations; each location is 1 byte → 256 KB. With 4 data lines each location is 4 bits: 262,144 × 4 bits = 1,048,576 bits = 128 KB.

  7. Which of the following are accepted by an 8086 assembler? MOV ES, [BX] · MOV [SI], DS · MOV AX, [DX] · XCHG [SI], [DI] · MOV BYTE PTR [DI], 300

    Answer

    The first two are valid: a segment register can be loaded from memory (8E 07) and written to memory (8C 1C). [DX] is invalid; DX is not an address register. XCHG cannot take two memory operands. 300 does not fit in a byte (at most 255); the assembler reports an error.

  8. What is the relative address in video memory of the last cell of the 80 × 25 text screen (row 24, column 79)? At which physical address is this cell's color byte?

    Answer

    (24 × 80 + 79) × 2 = 1999 × 2 = 3998 = 0F9Eh. The character is at B8000h + 0F9Eh = B8F9Eh and the color byte at the next address, B8F9Fh. Since the whole screen is 4000 bytes, the last byte is 0F9Fh.

  9. How many clock periods do the instructions MOV AX, [BX+SI+6] and MOV AX, [BX+DI+6] take on the 8086? What changes if the EA comes out as an odd address?

    Answer

    MOV from memory to a register is 8 periods plus the EA time. For [BX+SI+d] the EA is 11 and for [BX+DI+d] 12 periods: 19 and 20 periods. If the EA is odd, the word is read in two bus cycles and 4 periods are added to the time: 23 and 24 periods.

4.1.14Further reading

  • B. B. Brey, The Intel Microprocessors (8th ed.), Chapter 3 (Addressing Modes): data, program, and stack addressing modes with examples from the 8086 to the Pentium; it is the source closest to the addressing part of these notes.
  • Intel, 8086/8088 User's Manual: Programmer's and Hardware Reference: ModR/M encoding, the segment prefix, and the instruction timing table (including the EA times) are found here at first hand.
  • K. R. Irvine, Assembly Language for x86 Processors (7th ed.), Chapter 4: data transfer, little-endian, OFFSET, PTR, and indirect addressing; real-mode examples.
  • The emu8086 documentation, 8086 assembler tutorial for beginners, Part 2: Memory Access and MOV instruction; it is the source of the MOV examples in the slides.

4.1.15References

  1. The emu8086 documentation, 8086 assembler tutorial for beginners, part 2: memory access, MOV instruction.
  2. Intel, 8086/8088 User's Manual, addressing modes and instruction encoding.
  3. B. B. Brey, The Intel Microprocessors, 8th edition, Pearson, Chapter 3 (Addressing Modes).
  4. Documentation of IBM PC text-mode video memory (B800h) and the attribute byte.
  5. K. R. Irvine, Assembly Language for x86 Processors, 7th edition, Pearson.

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