Microprocessors · Lecture Notes
Chapter 4.2: Variables
A program's data is, in the end, nothing but bytes in memory. The 8086 reaches these bytes with 20-bit physical addresses; but working with an address such as 5A73:235B is both hard and error-prone for the programmer. Assembly language therefore lets us give names to memory locations: variables. These notes first describe how variables are defined with the DB, DW, and DD directives. They then show what the assembler does when it assigns them relative locations and in what order multi-byte values are written to memory. Next they extend the same idea to arrays, strings, and tables; treat the difference between a variable's value and its address through LEA and OFFSET; and introduce EQU constants, which occupy no memory at all, and the location counter. The last section traces, line by line, small programs that move, add, and compare data with variables and process 32-bit values. At each step it is shown how the instruction changes the registers, flags, and memory, and what happens on the 8086's buses.
Learning outcomes
- Define variables
- Define byte, word, and double-word variables and arrays with DB, DW, DD,
?, and DUP; apply the naming rules and value ranges. - Work out the memory layout
- Find at which relative location, and in which byte order, every instruction and every variable of a source program is placed; explain the effect of ORG 100h, the PSP, and alignment.
- Work with arrays
- Compute the byte offset of an element in byte and word arrays, strings, and two-dimensional tables, and access the element by index.
- Separate the address from the value
- Say what LEA, OFFSET, and a variable name load into a register; use pointer variables.
- Use constants
- Use EQU constants and the location counter (
$) to write values that occupy no memory and update themselves automatically. - Trace programs
- Trace step by step, at the register, flag, and memory level, programs that move, add, and compare data between variables and process 32-bit values.
4.2.1Variables
The 8086's memory is a long strip of one million bytes numbered from 00000h to FFFFFh. To reach a byte on this strip, the processor produces a 20-bit physical address from a segment register and an offset. Machine language knows only these numbers. A program that stores a counter, a sum, or a text in memory might have to write the data's address at every use. Such a program is very hard to read and to change. Moving a datum one byte over would mean correcting, one by one, every instruction in which that address appears.
Assembly language solves this problem with names. The programmer gives a memory location a meaningful name; the assembler takes over the job of computing the address and substituting it at every use. This section describes how named memory locations, that is, variables, are defined and how the assembler and the processor see them.
4.2.1.1What is a variable?
A variable is a data area in memory bound to a name, whose value can change while the program runs. A variable has three properties: its name, its address in memory (its relative location within the segment), and its type, which determines the number of bytes it occupies.
For the programmer, using the name var1 is much easier than using the address 5A73:235B. The name exists only in the source code. When the assembler translates the source file into machine code, it replaces every name with the relative location it has reserved for that variable. No name remains in the running program; the processor sees only the 16-bit relative location embedded in the instruction. The concept of a variable therefore lives not in the hardware but in the assembler.
The assembler supports two basic types. The BYTE type is 8 bits and is defined with DB (define byte). The WORD type is 16 bits, a word of the 8086, and is defined with DW (define word). A third directive, DD (define double word), reserves a 32-bit, that is, 4-byte, double word. The general form of a definition is as follows:
name DB value
name DW value
name DD valueThe following two lines define two variables, of one byte and two bytes:
counter DB 10h ; BYTE
sum DW 0FFFFh ; WORDcounter occupies a single byte and holds 10h. sum occupies two bytes: FFh and FFh at the addresses sum and sum+1.Figure 4.2.1 shows the memory counterpart of these two definitions. The assembler reserves one byte for counter and writes 10h into it. Right after it, it reserves two bytes for sum. The name sum stands for the address of the first of these two bytes. The second byte is reached with sum+1. No gaps are left between variables: definitions are laid out consecutively in memory in the order they are written in the source.
A directive is a source line that gives information to the assembler and is not itself translated into a processor instruction. ORG, END, and EQU produce no bytes. DB, DW, and DD, on the other hand, produce not instructions but data bytes: they write the given initial values into memory, into the program.
This distinction is important. A line such as MOV AL, counter is a machine instruction that the processor will execute. counter DB 10h is nothing to be executed; it only puts the value 10h into the program's byte image. When the program is loaded from disk into memory, this byte is loaded too and becomes the variable's initial value. There is no need to assign an initial value to the variable separately.
4.2.1.2Naming rules and the initial value
A variable name is a label and is written into the assembler's symbol table. It therefore has to obey some rules:
- A name starts with a letter; letters and digits may follow. MASM and emu8086 also accept the underscore and a few special characters (
_,@,$,?). - Register names (
AX,SI…) and instruction names (MOV,ADD…) are reserved words; they cannot be variable names. - The assembler does not distinguish upper and lower case:
VAR1,var1, andVar1are the same name. - The same name cannot be defined twice. This rule applies to constants and labels too.
A data definition does not have to have a name. The line DB 0Ah reserves a byte in memory and writes 0Ah into it; this byte has no name but it has an address. It can be reached by adding a number to the address of the preceding named variable. This is why, in multi-line tables, naming only the first line is enough.
The initial value can be written in any number form: decimal (10), hexadecimal (0Ah), binary (00001010b), octal (12o), or a character in quotes ('A'). The assembler converts all of them to the same binary pattern. For variables whose initial value does not matter, ? is written. ? means “the initial value of this area is undefined”; emu8086 puts 00 in these bytes, but it is wrong for a program to rely on that value.
| Definition | Result | Explanation |
|---|---|---|
num1 DB 5 | valid | a name that starts with a letter, one byte, value 05h |
1num DB 5 | invalid | the name starts with a digit |
ax DW 0 | invalid | a register name cannot be a variable name |
DB 0Ah | valid | nameless; reserves a byte, has an address |
result DW ? | valid | a word with no initial value; 00 00 in emu8086 |
letter DB 'A' | valid | the character's ASCII code: 41h |
4.2.1.3Value ranges
A byte has 8 bits, that is, 28 = 256 different patterns. These patterns can be interpreted in two ways. In the unsigned interpretation the patterns are the numbers 0 to 255. In the signed interpretation the two's-complement representation is used: if the top bit is 1 the number is negative, and the range is −128 to 127. For words and double words the same logic applies to 16 and 32 bits.
| Directive | Size | Unsigned | Signed | Example |
|---|---|---|---|---|
DB | 1 byte | 0 … 255 | −128 … 127 | x DB -1 → FF |
DW | 2 bytes | 0 … 65.535 | −32.768 … 32.767 | y DW -2 → FE FF |
DD | 4 bytes | 0 … 4.294.967.295 | −231 … 231 − 1 | z DD 1 → 01 00 00 00 |
When accepting an initial value, the assembler looks at the union of the two ranges. For DB, every number from −128 to 255 fits in a byte. When x DB -1 is written, the assembler computes the 8-bit two's complement of −1: the inverse of 1 is 1111 1110, plus 1 gives 1111 1111 = FFh. Had x DB 255 been written, FFh would again sit in memory. The two definitions produce the same byte in memory. DB 300, on the other hand, does not fit in a byte, because 300 = 12Ch needs nine bits; the assembler reports an error on this line and does not silently truncate the value.
In memory only the bit pattern is stored; the information about whether a byte is signed or unsigned is not in memory. The meaning of the pattern is determined by the instruction that uses it: JAE, JB, and CF interpret it as unsigned; JGE, JL, CBW, and OF interpret it as signed.
This definition prevents a common confusion when working with variables. Writing DB -1 does not tell the assembler “this variable is signed.” The programmer only chooses the initial pattern. The same FFh byte can be processed as 255 in one instruction and as −1 in the next. The trace below shows this step by step.
4.2.1.4Code trace: is FFh 255 or −1?
ORG 100h
MOV AL, x ; FFh
ADD AL, 1 ; 255 + 1 ?
MOV AL, x
CBW ; signed: −1
MOV BX, y ; FFFEh
NEG BX ; −(−2)
RET
x DB -1
y DW -2The program starts at 0100h. The seven instructions take 16 bytes in total (A0 10 01, 04 01, A0 10 01, 98, 8B 1E 11 01, F7 DB, C3); that is why x lands at 0110h and y at 0111h. In memory x = FFh, and y is the bytes FE FF in little-endian order, that is, FFFEh.
The line MOV AL, x is, in the assembler's eyes, MOV AL, [0110h]. The machine code is A0 10 01: the opcode A0 means “load into AL the byte at the 16-bit relative location that follows,” and the bytes 10 01 are 0110h. It is useful to remember that the execution unit (EU) does not itself access memory. The EU takes the relative location from the queue and hands the read job to the bus interface unit (BIU). The BIU computes the physical address as DS × 10h + 0110h and performs a read bus cycle. If emu8086's load segment is 0700h, the physical address is 07000h + 0110h = 07110h. Since this address is even, the byte comes over the low half of the data bus (D0–D7). The instruction takes 10 clock periods. As a result AL = FFh and AX = 00FFh. MOV does not change the flags.
ADD AL, 1 processes the pattern with an unsigned view. 1111 1111 + 0000 0001 = 1 0000 0000; the ninth bit does not fit in a byte. AL = 00h is left and the bit that spills out is written to the carry flag: CF = 1. Since the result is zero, ZF = 1. With the signed view the same addition is −1 + 1 = 0 and is correct; since there is no signed overflow, OF = 0 remains. A single addition writes the results of both interpretations into the flags at once: CF reports unsigned overflow and OF signed overflow. The program decides which to look at.
MOV AL, x makes AL FFh again; the flags keep their previous values. CBW (convert byte to word) takes AL as a signed number and extends it to 16 bits: it copies the top bit of AL into the eight bits of AH. The top bit of AL = FFh is 1; AH = FFh. AX = FFFFh, which is −1 in 16 bits. This operation is called sign extension. Had AL been thought of as unsigned 255, the correct 16-bit equivalent would be 00FFh; CBW does not make this choice, it always extends as signed. CBW takes only 2 clock periods and does not change the flags.
MOV BX, y reads the two bytes together: the FEh at 0111h goes to the low byte (BL) and the FFh at 0112h to the high byte (BH). BX = FFFEh, which is 65,534 in the unsigned view and −2 in the signed view. Because y sits at an odd address, the 8086 reads this word with two separate bus cycles. NEG BX takes the two's complement of the number, that is, computes 0 − BX: 0000h − FFFEh = 0002h. Because the operand is nonzero, NEG sets CF = 1. The result is not zero, so ZF = 0.
| Line | AX | BX | CF | ZF | OF | Interpretation |
|---|---|---|---|---|---|---|
2 MOV AL, x | 00FFh | 0000h | 0 | 0 | 0 | AL: 255 or −1 |
3 ADD AL, 1 | 0000h | 0000h | 1 | 1 | 0 | unsigned overflow: CF |
4 MOV AL, x | 00FFh | 0000h | 1 | 1 | 0 | flags preserved |
5 CBW | FFFFh | 0000h | 1 | 1 | 0 | sign extension: −1 |
6 MOV BX, y | FFFFh | FFFEh | 1 | 1 | 0 | 65,534 or −2 |
7 NEG BX | FFFFh | 0002h | 1 | 0 | 0 | 0 − (−2) = 2 |
ADD AL, 1: AL = 00h, and the unsigned overflow is reported by CF = 1. On the right, after CBW: AL = FFh is taken as signed −1 and extended to AX = FFFFh.Table 4.2.3 and Figure 4.2.2 show two faces of the same program. The two variables in memory never changed; what changed is the interpretation of the instructions that read the patterns. ADD and CF treated the pattern as unsigned, CBW and NEG as a signed number.
It is wrong to assume that a variable defined with x DB -1 will behave like a negative number from then on. The assembler converts -1 only into the pattern FFh and records the type as BYTE; it does not keep the sign information. If this variable is compared with JAE, it behaves like 255.
4.2.1.5The variable's type and size checking
The assembler also writes a type next to every variable name. A name defined with DB has type BYTE (1 byte), one defined with DW has type WORD (2 bytes), and one defined with DD has type DWORD (4 bytes). The type determines how many bytes of the variable an instruction reads or writes, and provides a safety check at assembly time.
The rule is simple: if the other operand in the instruction is a register, the register's size and the variable's type must match. MOV AX, w is valid, because both AX and w are 16 bits. MOV AL, w is invalid; the assembler reports a “1 byte / 2 bytes” mismatch and stops assembly. If the other operand is a constant, the variable's type determines how many bits of the constant are written: MOV w, 5 writes two bytes, 05 00, to memory.
Memory operands that contain no variable name have no type. [BX] says only an address; it does not say whether there is a byte or a word at that address. So MOV [BX], 5 is ambiguous and gives an error. The programmer writes the size explicitly with BYTE PTR or WORD PTR: MOV BYTE PTR [BX], 5. The same specifier also serves to change a variable's type for that instruction only: MOV AL, BYTE PTR w reads the low byte of the word variable. The variable's definition and type do not change.
| Instruction | Result |
|---|---|
MOV AL, w | error: operand sizes do not match (1 byte / 2 bytes) |
MOV AL, BYTE PTR w | AL = 34h (low byte) |
MOV AL, BYTE PTR w+1 | AL = 12h (high byte) |
MOV w, 5 | w = 0005h; 05 00 is written to memory |
MOV AX, b | error: operand sizes do not match (2 bytes / 1 byte) |
MOV [BX], 5 | error: size is ambiguous; BYTE PTR or WORD PTR is needed |
MOV b, w | error: there is no memory-to-memory MOV |
INC b | b = 06h; only one byte is incremented |
Type checking is done only at assembly time. The processor knows no types while running. The size of an instruction is encoded in the machine code with a bit: in most 8086 opcodes the lowest bit (the W bit) means the operation is on a byte if 0 and on a word if 1. For example MOV AL, [address] is encoded with A0 and MOV AX, [address] with A1. The assembler chooses the right W bit by looking at the variable's type. Had an access of the wrong size got through assembly, the processor would have executed it without objection. The size error the assembler gives therefore works in the programmer's favor: it catches, right from the start, an error that produces a wrong value and is hard to notice.
The error in the line MOV b, w, on the other hand, is not a type error but a hardware rule. None of the 8086's data-movement instructions takes two memory operands. The instruction format has only one ModR/M field, and this field can define at most one memory operand. A memory-to-memory move is always done through a register with two instructions.
4.2.1.6Two names for the same memory with LABEL
Sometimes the same memory area is to be processed both byte by byte and as a word. Writing BYTE PTR or WORD PTR at every access is possible but not readable. The LABEL directive instead gives a second name and type to the same address.
The directive name LABEL type reserves no memory. It gives a new name, of the stated type (BYTE, WORD, DWORD), to the address of the first byte that follows it.
ORG 100h
MOV AX, wval ; WORD
MOV BL, bytes ; low
MOV BH, bytes+1 ; high
MOV bytes, 0FFh ; one byte
MOV CX, wval ; word
RET
wval LABEL WORD
bytes DB 34h, 12hThe six instructions fill the range 0100h to 0114h; RET is at 0114h. Since wval LABEL WORD produces no bytes, both wval and bytes point to address 0115h. In memory 34h sits at 0115h and 12h at 0116h.
MOV AX, wval uses a name of type WORD, so it reads both bytes at once: AX = 1234h. The assembler encodes this line as A1 15 01. MOV BL, bytes uses the BYTE-type name of the same address and reads only 34h; there is no need to write PTR. MOV BH, bytes+1 reads the second byte: BH = 12h. BX = 1234h. The same result as AX is the natural outcome of the little-endian order: the byte at the low address goes to the low half.
In the line MOV bytes, 0FFh the destination's type is BYTE. The assembler produces the 5-byte instruction C6 06 15 01 FF, and the processor writes only to address 0115h. Memory is now FF 12. The last read, MOV CX, wval, takes the same two bytes as a word: CX = 12FFh. A change made through the byte name is seen through the word name, because the two names point to a single memory location.
| Line | AX | BX | CX | [0115h] [0116h] |
|---|---|---|---|---|
2 MOV AX, wval | 1234h | 0000h | 0000h | 34 12 |
3 MOV BL, bytes | 1234h | 0034h | 0000h | 34 12 |
4 MOV BH, bytes+1 | 1234h | 1234h | 0000h | 34 12 |
5 MOV bytes, 0FFh | 1234h | 1234h | 0000h | FF 12 |
6 MOV CX, wval | 1234h | 1234h | 12FFh | FF 12 |
MOV AX, wval: the two bytes are read as a WORD. On the right MOV bytes, 0FFh: because of the BYTE type only 0115h changes; wval is now 12FFh.LABEL is used in programs that process a buffer both as bytes and as words. For example, a serial-port buffer is filled byte by byte but compared two bytes at a time. The program size grows only by the two bytes of the DB line; the LABEL line leaves no trace in memory.
4.2.2Memory layout
Defining a variable means asking the assembler for space in memory. Knowing exactly where this space is, is indispensable when tracing a program and debugging. Only someone who knows the layout can read in a memory dump which byte belongs to which variable, and which number in an instruction's machine code is an address. This section follows how a small program turns into bytes from start to finish.
4.2.2.1A sample program and its byte image
ORG 100h
MOV AL, var1 ; AL ← var1
MOV BX, var2 ; BX ← var2
RET ; end the program
VAR1 DB 7 ; BYTE, 7
var2 DW 1234h ; WORD, 1234hThe layout of the program is deliberately chosen: code first, then data. Since the variables sit after the RET, the processor never reaches them. Execution ends at RET; the bytes behind it are read only as data. In the source the variable's name is written once as VAR1 and once as var1. Since the assembler is case-insensitive, the two are the same variable.
VAR1 at 0108h, var2 at 0109h–010Ah. The variable names have turned into relative locations inside the instructions.The assembler translates the source file into the 11-byte sequence in Figure 4.2.4. The first instruction MOV AL, var1 is three bytes: A0 08 01. A0 is the short opcode that loads a byte from a direct address into AL, and the two bytes that follow are the address itself: 0108h. The second instruction MOV BX, var2 is four bytes: 8B 1E 09 01. The opcode 8B means “load a word register from memory,” the byte 1E (ModR/M) says the destination is BX and the address is given directly in the instruction, and 09 01 is 0109h. The third instruction is the single-byte C3 (RET). Then comes the data: 07 at 0108h, 34 at 0109h, and 12 at 010Ah.
Two points stand out in this image. First, there is no name in the machine code; var1 and var2 have given way to the numbers 0108h and 0109h. Second, even the addresses are written little-endian: 0108h sits in the instruction in the order 08 01. The little-endian order applies not only to data but to every 16-bit number embedded in an instruction.
In little-endian order, the low byte of a multi-byte value goes to the low address and the high byte to the next address. The 8086 is little-endian: DW 1234h sits in memory as 34 12, and DD 12345678h as 78 56 34 12.
This order matches the 8086's hardware. The low half of the 16-bit data bus (D0–D7) carries the even-addressed byte and the high half (D8–D15) the odd-addressed byte. When a word starting at an even address is read, the low byte automatically arrives in the low half of the register and the high byte in the high half. No byte swapping is needed.
4.2.2.2Code trace: var1 and var2
When tracing the program step by step, seeing IP advance by the length of the instruction after each instruction is the easiest way to verify the byte image.
| Line | Machine code | IP | AL | BX | Explanation |
|---|---|---|---|---|---|
1 ORG 100h | — | 0100h | 00h | 0000h | initial state after loading |
2 MOV AL, var1 | A0 08 01 | 0103h | 07h | 0000h | [0108h] is read |
3 MOV BX, var2 | 8B 1E 09 01 | 0107h | 07h | 1234h | [0109h] and [010Ah] are read |
4 RET | C3 | 0000h | 07h | 1234h | 0000h popped from the stack; INT 20h in the PSP |
MOV AL, [0108h]: AL = 07h, IP = 0103h. On the right, after MOV BX, [0109h]: 34h goes to the low byte and 12h to the high byte, BX = 1234h, IP = 0107h.In the first step the processor executes the three bytes at 0100h. The BIU computes the physical address as DS × 10h + 0108h and fetches 07h with a single read bus cycle. AL = 07h, IP = 0103h. In the second step the address is 0109h, which is odd. The low byte of the word is at 0109h and the high byte at 010Ah. These two bytes do not fall on the same half of the data bus. The 8086 first reads 0109h from the high half and then 010Ah from the low half, and arranges the two bytes in the right order in BX. The result is BX = 1234h; IP advances four bytes to 0107h.
The last instruction is RET. When a .COM program starts, DOS puts the value 0000h on the stack: SP = FFFEh, [FFFEh] = 0000h. RET takes this word into IP and increases SP by 2: IP = 0000h, SP = 0000h. At relative location 0000h of the segment is the PSP header in front of the program, and its first two bytes are CD 20, that is, INT 20h. This interrupt terminates the program and hands control back to DOS. That is why IP in the RET row of the trace table is 0000h, not 0108h. The data byte at 0108h is never executed as an instruction.
The trace in the slides assumes the program is loaded into segment 0B56h: DS = CS = 0B56h, and the full address of VAR1 is 0B56:0108. emu8086, on the other hand, loads .COM programs into segment 0700h; the full address of the same variable there is 0700:0108. The two notations do not contradict. The segment value depends on where DOS loads the program in memory and may change on every run. The relative locations, however, are fixed at assembly time. Since the program uses only relative locations, it works the same wherever it is loaded.
4.2.2.3What does the assembler do?
While translating source code into a byte sequence, the assembler does two jobs together. It turns instructions into machine code and replaces variable names with relative locations. To be able to do this, it keeps a counter while reading the source file from start to finish.
The location counter is the counter in which the assembler holds the relative location where the next byte will be placed. ORG sets it to a given value; every instruction and every data definition increases it by the number of bytes it produces. In the source it is read with the symbol $.
In the sample program ORG 100h makes the counter 0100h. Since MOV AL, var1 produces three bytes, the counter becomes 0103h; MOV BX, var2 produces four bytes and the counter is 0107h; after RET it is 0108h. When the assembler reaches the VAR1 definition, it writes the counter's current value, 0108h, into the symbol table as this name's address. Since DB 7 produces one byte, the counter becomes 0109h, and var2 takes this address.
There is a problem here. The line MOV AL, var1 comes before the VAR1 definition. When the assembler reaches this line, it does not yet know the address of VAR1. The solution is to read the source twice. In the first pass only the number of bytes each line will take is computed and the symbol table is filled. In the second pass, since all the addresses are known, the machine code is produced. This is why variables can be defined after the place where they are used in the source.
A variable's relative location is its distance in bytes from the start of the segment. The relative location of VAR1 is 0108h. The full (logical) address is written with the segment value: 0B56:0108. The physical address is 0B56h × 10h + 0108h = 0B560h + 0108h = 0B668h. var2 is at 0109h, its full address is 0B56:0109, and since it is of type WORD it occupies 0109h and 010Ah.
When .COM programs are loaded, DOS gives all four segment registers the same value: CS = DS = ES = SS. Code and data therefore sit in the same segment, and there is no need to load DS separately to access a variable. The relative location in the instruction finds the right place in the segment DS points to.
4.2.2.4The ORG 100h directive and the .COM program
The ORG (origin) directive tells the assembler the starting value of the location counter. ORG 100h declares that the first byte of the program will be loaded at relative location 0100h of the segment. The assembler takes this value into account when replacing variable names with addresses. If ORG is forgotten, the counter starts at 0000h and every variable address is computed 100h lower than its real place. The program assembles without an error but reads the wrong bytes. That is why emu8086 assumes 100h for .COM sources in which ORG is not written. ORG is a directive; it is not translated into machine code and produces no bytes.
Why 100h? When loading a .COM program, DOS places a header called the PSP (program segment prefix) in the first 256 bytes of the segment (0000h–00FFh). The PSP holds information about the program: at 0000h the INT 20h that ends the program, at 80h the length of the command line, and between 81h and FFh the command-line parameters. The program starts right after this header, at 0100h. The stack is at the very top of the segment: it starts with SP = FFFEh and grows downward. Code, data, and stack share a single 64 KB segment (Figure 4.2.6).
The layout of .EXE programs is different. The code segment of an .EXE file starts at relative location 0000h and a separate data segment is used for the variables. Since each segment can grow up to 64 KB, large programs are written in the .EXE format. In this course most of the examples are written with emu8086's .COM template; a single segment makes it easier to follow the addresses of the variables.
4.2.2.5Alignment and EVEN
The address at which a word variable starts does not affect the correctness of the program, but it affects its speed. The reason is the 8086's memory interface.
The 8086's memory is divided into two banks. Even-addressed bytes sit in the low bank and are connected to the data lines D0–D7. Odd-addressed bytes sit in the high bank and are connected to D8–D15. The processor signals which bank it selects with two signals: if the address line A0 is 0 the low bank is active, and if the BHE (bus high enable) signal is 0 the high bank is active. For a word starting at an even address, A0 = 0 and BHE = 0 are given at the same time; the two bytes arrive together in a single bus cycle.
In a word starting at an odd address, the two bytes are on different lines. The byte at 0201h is in the high bank, and the byte at 0202h is in the low bank of the next line. The 8086 notices this by itself and performs two bus cycles: first it reads 0201h from the high half, then 0202h from the low half. The program still gets the right value; only, because each cycle takes four clock periods, 4 periods are lost per word access.
The instruction MOV AX, w takes 10 clock periods on the 8086; if w is at an odd address it takes 14. If this instruction is executed 1000 times in a loop, the difference is 1000 × 4 = 4000 periods. On a 5 MHz 8086 one period is 1 / 5 MHz = 200 ns. The total loss is 4000 × 200 ns = 800,000 ns = 0.8 ms.
To ensure aligned placement, the EVEN directive is used in MASM and TASM. If the location counter is odd, EVEN rounds it up to an even number by increasing it by one and puts a padding byte in between; if the counter is already even, it does nothing. In the code segment the padding is usually the byte 90h (NOP). The definitions do not move; they only shift.
a DB 5 ; 0200h
EVEN ; 0201h: pad
w DW 1234h ; 0202h (even)a lands at 0200h and the counter becomes 0201h. EVEN rounds the counter up to 0202h and puts a padding byte at 0201h. w starts at an even address; memory holds 05, padding, 34, 12. Alignment is not needed for byte variables, because a single byte is read in a single bus cycle at every address. On the 8088, whose data bus is 8 bits, every word needs two bus cycles anyway; there alignment makes no difference.
4.2.2.6Where do variables go?
The processor does not distinguish whether the bytes in memory are code or data. Whatever byte IP points to, it decodes as an instruction. Where in the program the variables are written is therefore important: data bytes that fall on the execution path are taken for instructions. There are three common layouts.
| Place | Example | Points to watch |
|---|---|---|
| At the end of the code | RET · x DB 5 | Execution ends at RET and never reaches the data. The most commonly used layout in .COM. |
| At the start of the code | JMP start · x DB 5 · start: | JMP skips the data; if forgotten, the data bytes are executed as instructions. |
| Separate data segment (.EXE) | .DATA · x DB 5 | MOV AX, @data · MOV DS, AX is mandatory at the start of the program. |
The first layout is used in most of the programs in these notes. In the second layout the data are at the start of the program and the first instruction is a JMP. This layout has one advantage: the addresses of the variables are not affected by changes in the code. However the code grows or shrinks, the data right after the JMP always stay at the same relative location. For example, after a 2-byte short JMP the first variable is always at 0102h. If the JMP is forgotten, the processor decodes the data bytes at 0100h as instructions. For example, the bytes 0A 00 of DW 10 are executed as OR AL, [BX+SI]; the program does meaningless things without giving an error.
The third layout is specific to .EXE programs. Code sits in the segment CS points to and data in the segment DS points to. The relative locations of the variables are computed from the start of the data segment. When the program starts, DOS sets DS not to the program's data but to the PSP. That is why the first two instructions of an .EXE program load DS. @data is the segment value of the data segment. Since an immediate value cannot be loaded into a segment register, the value is first taken into AX.
Forgetting the lines MOV AX, @data · MOV DS, AX in an .EXE program. MOV AL, x uses the right relative location but reads from the wrong segment, the one where the PSP is. Neither the assembler nor the processor reports an error; the program just gets a wrong value. In .COM programs this problem does not arise, because CS = DS.
4.2.3Arrays
Single variables are enough for small programs. But for a hundred measurements read from a sensor, the letters of a text, or a conversion table, defining a hundred separate names is both impossible and pointless. Data of this kind is stored as consecutive bytes of the same type and referred to by a single name: an array.
4.2.3.1The array concept
An array is a set of elements of the same type placed in consecutive locations in memory. The name of the array stands for the address of the first element; the later elements follow right behind it. An element is reached by adding the element's byte offset to the address of the array.
An array can be thought of as a chain of variables. If several values separated by commas are written after a DB or DW directive, the assembler lays them all out in order with no gaps between them. A text in quotes also turns into a byte array automatically: for each character its ASCII code is written.
a DB 48h, 65h, 6Ch, 6Ch, 6Fh, 00h
b DB 'Hello', 0a and b sit one after the other in memory. The two definitions produce the same bytes: 48h 'H', 65h 'e', 6Ch 'l', 6Ch 'l', 6Fh 'o', and the string terminator 00h.The two definitions in Figure 4.2.8 are written differently but produce the same six bytes in memory. a gives the numbers in hexadecimal; b writes the text in quotes and the assembler converts each letter to its ASCII code. The 0 at the end is a terminator and shows where the string ends. As far as memory is concerned, there is no difference between a “text” and a “number array”; both are byte arrays.
4.2.3.2Code trace: accessing array elements
ORG 100h
MOV AL, a[3] ; a + 3
MOV SI, 0
MOV BL, a[SI] ; a + 0
INC SI
MOV BH, a[SI] ; a + 1
MOV a[SI], 'E' ; a[1] ← 45h
RET
a DB 48h,65h,6Ch,6Ch,6Fh,0The program begins with ORG 100h: the code is loaded from 0100h. The seven instructions take 21 bytes; the array a starts at 0115h. An array element is accessed in two ways: with a constant index or with a register.
MOV AL, a[3] is a constant-index access. The number inside the square brackets is not the element number but the byte offset: a[3] means “add 3 to the address of a.” Since the offset is known at assembly time, the assembler does the addition itself: 0115h + 3 = 0118h. The instruction turns into MOV AL, [0118h] with a direct address and is encoded as A0 18 01. The byte at 0118h is 6Ch; AL = 6Ch, that is, 'l'. The processor does no addition while running.
MOV SI, 0 clears the index register. MOV BL, a[SI] is an access with a register: the address is computed at run time as a + SI. This time the machine code is 8A 9C 15 01. The ModR/M byte 9Ch says the address is “SI + a 16-bit displacement,” and the displacement is the array's address, 0115h. The EU computes the effective address as 0115h + SI = 0115h and the BIU reads that byte: BL = 48h ('H').
INC SI increments the index; SI = 1 now points to the second element. The MOV BH, a[SI] instruction, in the same form, this time reads 0116h: BH = 65h ('e'). BX = 6548h. Here the basic idea of a loop is seen: the instruction stays the same, only the index register changes. A loop can scan the whole array with the same instruction by incrementing SI on each iteration.
MOV a[SI], 'E' writes into the array. Since the destination a is of type BYTE, there is no size ambiguity; the assembler produces the instruction C6 84 15 01 45 and a single byte is written: [0116h] = 45h. The array is now “HEllo.” 'E' is a character constant in quotes and, to the assembler, no different from the number 45h.
| Line | Effective address | AL | SI | BX | Array |
|---|---|---|---|---|---|
2 MOV AL, a[3] | 0118h | 6Ch | 0000h | 0000h | H e l l o 0 |
3 MOV SI, 0 | — | 6Ch | 0000h | 0000h | H e l l o 0 |
4 MOV BL, a[SI] | 0115h | 6Ch | 0000h | 0048h | H e l l o 0 |
5 INC SI | — | 6Ch | 0001h | 0048h | H e l l o 0 |
6 MOV BH, a[SI] | 0116h | 6Ch | 0001h | 6548h | H e l l o 0 |
7 MOV a[SI], 'E' | 0116h | 6Ch | 0001h | 6548h | H E l l o 0 |
a[3] = a + 3 bytes, AL = 6Ch ('l'). On the right the last write: a[1] ← 45h; the array becomes “HEllo.”The two access paths have different costs in hardware. MOV AL, [0118h] takes 10 clock periods. MOV BL, a[SI], on the other hand, computes the effective address as “displacement + index”; this calculation adds 9 periods on the 8086, and the instruction takes 8 + 9 = 17 periods. A constant-index access is faster but not flexible; an index register lets each iteration access a different element.
4.2.3.3Access forms and DUP
All forms of accessing an array element come down to the same effective address calculation. On the 8086 only BX, BP, SI, and DI can be used inside square brackets; these four registers can work as memory index registers. MOV SI, 3 · MOV AL, a[SI] and MOV AL, a[3] read the same byte. The assembler treats the following notations as equivalent:
a[SI] = [a + SI] = [SI + a] = [SI]+aWhichever is written, the machine code is the same: the address is the sum of the index register and a 16-bit displacement. The index is always in bytes. In a byte array the offset of the i-th element is i, but in a word array it is 2 × i. Unlike high-level languages such as C, the assembler does not multiply by the element size for the programmer.
For large arrays it is not necessary to write every value out. The DUP (duplicate) operator repeats a list of values the required number of times.
The expression count DUP(value(s)) writes the list of values in the parentheses count times in a row. If ? is written in the parentheses, an area with no initial value is reserved; DUP can be nested.
c DB 5 DUP(9)is the same asc DB 9, 9, 9, 9, 9: 5 bytes.d DB 5 DUP(1, 2)is the same asd DB 1, 2, 1, 2, 1, 2, 1, 2, 1, 2: 10 bytes. What is repeated is not a single value but the whole list.buffer DB 100 DUP(?)reserves a 100-byte area with no initial value. It is the usual way to make room for a line read from the keyboard or a calculation result.table DW 10 DUP(0)reserves 10 words, that is, 20 bytes, and zeroes them all.
DUP: 5 DUP(9) gives five 09s, 5 DUP(1, 2) ten bytes: the pair 01 02 five times.Arrays are also defined with DW: w DW 1000h, 2000h is a number array of two words. Values greater than 255 or less than −128 do not fit in a byte, so such numbers need DW. One place where DW cannot be used is long texts: DW 'Hello' is invalid. A word can hold at most two characters; there is no single meaningful way to split a five-character text into words. Texts are always defined with DB.
4.2.3.4Word arrays
In a word array each element occupies two bytes. The element number and the byte offset then come apart, and the most frequent array mistake appears exactly at this point.
ORG 100h
MOV AX, w[0] ; element 1
MOV BX, w[2] ; element 2
MOV SI, 4
MOV CX, w[SI] ; element 3
MOV DX, w[1] ; careful!
RET
w DW 1111h, 2222h, 3333hThe code starts at 0100h and takes 19 bytes; w is at 0113h. In memory the bytes 11 11 22 22 33 33 sit from 0113h on. MOV AX, w[0] reads the first word: AX = 1111h. The second element is not at w[1] but at w[2], because the first element occupies two bytes: BX = 2222h. The general rule is that the offset of the i-th element (counting from 0) is 2 × i. The index of the third element is 2 × 2 = 4: with MOV SI, 4 · MOV CX, w[SI], CX = 3333h.
The last line MOV DX, w[1] is wrong, but the assembler does not notice. Offset 1 is the middle of the first element. The instruction reads the word starting at 0114h: the low byte is the 11h at 0114h and the high byte the 22h at 0115h. DX = 2211h. This value is not any element of the array; it consists of one half each of two neighboring elements. In the same way w[3] combines the high byte of 2222h with the low byte of 3333h and gives 3322h. In a word array the index must always be even.
| Line | Addresses read | AX | BX | CX | DX | SI |
|---|---|---|---|---|---|---|
2 MOV AX, w[0] | 0113h, 0114h | 1111h | 0000h | 0000h | 0000h | 0000h |
3 MOV BX, w[2] | 0115h, 0116h | 1111h | 2222h | 0000h | 0000h | 0000h |
4 MOV SI, 4 | — | 1111h | 2222h | 0000h | 0000h | 0004h |
5 MOV CX, w[SI] | 0117h, 0118h | 1111h | 2222h | 3333h | 0000h | 0004h |
6 MOV DX, w[1] | 0114h, 0115h | 1111h | 2222h | 3333h | 2211h | 0004h |
w[0]: AX = 1111h. On the right w[1]: the high byte of the first element and the low byte of the second combine, DX = 2211h.In Table 4.2.9 note that w starts at an odd address (0113h). In this layout each of w[0], w[2], and w[4] is a word at an odd address, and every read needs two bus cycles. Had an EVEN been written before the DW line, the array would start at 0114h and every element would be read in a single bus cycle. In that case the wrongly indexed w[1] would have fallen on an odd address.
Trying to access the i-th element of a word array with w[i]. The third element is not at w[2] but at w[4]. In loops the index register is incremented by 2, not 1, on each iteration: ADD SI, 2.
4.2.3.5From definition to bytes
Being able to work out on paper which bytes a data definition produces in memory is necessary for reading memory dumps. The rule is always the same: values are written from left to right in order, each value occupies as much space as the type's size, and multi-byte values are in little-endian order. Table 4.2.10 gives the expansion of frequently met definitions.
| Definition | Bytes | Size |
|---|---|---|
b DB 'Hello', 0 | 48 65 6C 6C 6F 00 | 6 bytes |
a DB 48h, 65h, 6Ch, 6Ch, 6Fh, 00h | 48 65 6C 6C 6F 00 | 6 bytes |
var2 DW 1234h | 34 12 | 2 bytes |
d DB 5 DUP(1, 2) | 01 02 01 02 01 02 01 02 01 02 | 10 bytes |
w DW 3 DUP(?), -1 | ?? ?? ?? ?? ?? ?? FF FF | 8 bytes |
mydouble DD 12345678h | 78 56 34 12 | 4 bytes |
x DB 300 | error: 300 does not fit in a byte | — |
The line w DW 3 DUP(?), -1 has two parts. First three words with no initial value, that is, six bytes, are reserved; emu8086 writes 00 into them. Then −1 is added as a word. The 16-bit two's complement of −1 is FFFFh and is written in little-endian order as FF FF. The total size of the line is 8 bytes. Although the definition has a single name, it has four elements.
4.2.3.6Strings and terminators
A string is a text made of consecutive character codes in memory. The place where the string ends is shown by a terminator byte (0 or '$') or by a length byte at the start.
Memory does not know where a string ends. A program that prints or copies a string has to find the end point by a rule. There are three common rules:
s1 DB 'Welcome', 0 ; zero-terminated
s2 DB 'Welcome$' ; '$'-terminated (INT 21h / AH = 09h)
s3 DB 13, 10, 'Line', 13, 10, '$' ; CR LF: carriage return + line feed
s4 DB 7, 'Welcome' ; length-prefixed: first byte = 7
s5 DB "Ali's", 0 ; single quote inside double quotes| Form | How is the end recognized? | Where is it used? |
|---|---|---|
| zero-terminated | when the byte read is 0 | emu8086.inc PRINT_STRING, the C language |
| '$'-terminated | when the byte read is 24h | DOS string-printing service |
| length-prefixed | as many as the number in the first byte | DOS line-input buffer (AH = 0Ah) |
The space a string occupies in memory is the sum of the number of characters and the terminator. s1 is seven letters and a zero, that is, 8 bytes. The numbers 13 and 10 in s3 are not characters but control codes: 13 (0Dh) is carriage return (CR) and 10 (0Ah) is line feed (LF). In DOS, to end a line and go to the start of the line below, the two are written together. s4 is the length-prefixed form: the first byte is 7, followed by seven characters. In this form no terminator is needed and the length of the string is learned with a single read. s5 writes a text containing a single quote with double quotes; the assembler accepts both kinds of quotes.
If the terminator is forgotten, the code that prints the string does not stop. It takes the bytes behind the string for characters too and prints meaningless marks on the screen until it finds a 0 or '$'. A '$'-terminated string cannot print the '$' character itself, because it stops the moment it sees it. The codes of Turkish letters (ç, ğ, ı, ö, ş, ü), on the other hand, depend on the code page in use. These letters are not in the ASCII range 0–127; the same byte may appear as a different letter in a different code page.
4.2.3.7Character constants and ASCII arithmetic
A character in quotes is only a number to the assembler. MOV AL, 'A' and MOV AL, 41h produce the same machine code (B0 41). The layout of the ASCII table makes it possible to do simple arithmetic on characters.
| Characters | ASCII codes |
|---|---|
| '0' … '9' | 30h … 39h |
| 'A' … 'Z' | 41h … 5Ah |
| 'a' … 'z' | 61h … 7Ah |
| space · '$' | 20h · 24h |
| CR · LF | 0Dh · 0Ah |
The digit characters start at 30h and are in order. To obtain a number's value from a digit character it is therefore enough to subtract '0': '7' = 37h, 37h − 30h = 7. SUB AL, '0' does this job. In the reverse direction, to print a number between 0 and 9 on the screen, ADD AL, '0' is used. Every digit read from the keyboard is an ASCII code; it goes through this conversion before entering a calculation.
The difference between upper- and lower-case letters is 20h: 'a' = 61h, 'A' = 41h. 20h in binary is 0010 0000; that is, the two letters differ only in bit 5. In a lower-case letter bit 5 = 1 and in an upper-case letter it is 0. So to capitalize a letter it suffices to clear bit 5: SUB AL, 20h or AND AL, 0DFh. The mask 0DFh = 1101 1111 preserves all bits except bit 5. For example 'q' = 71h, 71h AND DFh = 51h = 'Q'. To lowercase a letter, bit 5 is set: OR AL, 20h; 'Q' = 51h, 51h OR 20h = 71h = 'q'.
Applying AND AL, 0DFh to all the bytes of a string without checking whether they are letters. Digits also have bit 5 = 1: '1' = 31h, 31h AND DFh = 11h and the digit turns into a control code. Before the conversion, the condition 'a' ≤ AL ≤ 'z' is tested.
4.2.3.8Code trace: converting a string to upper case
The program below converts a zero-terminated string to upper case in place. It does not know the length; it stops when it sees the terminator. The letter check keeps the digits from being corrupted.
ORG 100h
LEA SI, s
again:
MOV AL, [SI]
CMP AL, 0 ; terminator?
JE done
CMP AL, 'a'
JB next
CMP AL, 'z'
JA next
SUB AL, 20h ; 'a' - 'A'
MOV [SI], AL
next:
INC SI
JMP again
done:
RET
s DB 'Ab1c', 0The code is 25 bytes and fills 0100h–0118h; the string starts at 0119h. LEA SI, s loads the string's address into SI: SI = 0119h. SI is from then on a pointer to the character being processed. The body of the loop follows the same sequence on every iteration:
MOV AL, [SI]reads the next byte.CMP AL, 0andJE done: if the byte is 0, ZF = 1 and the loop ends.CMP AL, 'a'andJB next: if AL < 61h (CF = 1), the byte is not a lower-case letter; it is passed over without writing.CMP AL, 'z'andJA next: if AL > 7Ah, it is again passed over.- A byte that passes these two checks is a lower-case letter:
SUB AL, 20hcapitalizes it andMOV [SI], ALwrites it back to the same address. INC SImoves on to the next byte andJMP againreturns to the start.
The comparisons are made with unsigned jumps (JB, JA), because ASCII codes are unsigned numbers. When 'A' = 41h is compared with 'a' = 61h, the operation 41h − 61h needs a borrow and CF = 1; JB is taken.
| Round | SI | AL (read) | Decision | Written | String after |
|---|---|---|---|---|---|
| 1 | 0119h | 41h 'A' | 41h < 61h: JB taken | — | A b 1 c 0 |
| 2 | 011Ah | 62h 'b' | 61h ≤ 62h ≤ 7Ah: a letter | 42h 'B' | A B 1 c 0 |
| 3 | 011Bh | 31h '1' | 31h < 61h: JB taken | — | A B 1 c 0 |
| 4 | 011Ch | 63h 'c' | letter | 43h 'C' | A B 1 C 0 |
| 5 | 011Dh | 00h | ZF = 1: JE done | — | A B 1 C 0 |
CMP AL, 0 makes ZF = 1 and the loop ends.At the end of the program SI = 011Dh, AL = 00h, and ZF = 1; the string in memory has become “AB1C.” The loop read five times but wrote only twice. The program used the string's length nowhere; the terminator became the stopping condition instead of a counter. The code works unchanged whether characters are added to or removed from the string. The digit '1' was preserved because it was caught by the letter check; without the check it would have been corrupted by 31h − 20h = 11h.
4.2.3.9Two-dimensional arrays
A matrix or a table is a two-dimensional structure with rows and columns. Memory, however, is one-dimensional. When a two-dimensional array is placed in memory, the rows are laid out one after another.
In row-major order all the columns of row 0 are placed first, then all the columns of row 1. In a table with S columns, the byte offset of the element [row][column] from the start of the table is (row × S + column) × element size.
mat DB 3 DUP(4 DUP(0)) ; 3 × 4
tab DW 3 DUP(4 DUP(0)) ; 24 bytesA nested DUP reserves rows and columns together: “3 times (4 times 0).” mat is 12 bytes and tab 12 words, that is, 24 bytes. No trace of the nested structure is left in memory; there are only 12 or 24 consecutive bytes. What makes the table a table is the formula the program uses when computing the offset.
In the byte table in Figure 4.2.13 the offset of the element [2][1] is 2 × 4 + 1 = 9. In a word table the same calculation is multiplied by 2. For example, the element [1][2] of tab starts at byte (1 × 4 + 2) × 2 = 12. The number of rows does not appear in the formula. The number of rows does not affect the layout; it only determines the largest value the row index can take.
If the number of columns is a power of 2, shifting can be used instead of multiplication. For four columns, row × 4 is the same as shifting the row left twice: SHL AL, 1 twice. On the 8086 an 8-bit MUL takes 70–77 clock periods while each SHL takes 2. This is why table sizes are so often chosen as powers of 2.
4.2.3.10Code trace: reading a table element
NCOLS EQU 4
ORG 100h
MOV AL, row ; AL = 2
MOV BL, NCOLS ; BL = 4
MUL BL ; AX = 2 × 4
ADD AL, col ; + 1
MOV SI, AX ; SI = 9
MOV DL, mat[SI] ; mat[2][1]
RET
mat DB 11h, 12h, 13h, 14h
DB 21h, 22h, 23h, 24h
DB 31h, 32h, 33h, 34h
row DB 2
col DB 1The elements of the table were chosen to carry the row and column numbers: 32h is column 2 (index 1) of row 3 (index 2). The code fills 0100h–0111h; mat is at 0112h, row at 011Eh, and col at 011Fh. Only the first row is named. The next two DB lines are nameless and sit right after the first row.
MOV AL, row takes the row index from memory: AL = 2. MOV BL, NCOLS uses a constant. NCOLS EQU 4 occupies no memory; the assembler encodes this line as MOV BL, 4 (B3 04). MUL BL multiplies AL and BL as unsigned numbers and writes the 16-bit result to AX: AX = 2 × 4 = 0008h. This is the starting offset of row 2 in the table. Since the upper half of the result (AH) is 0, CF = OF = 0.
ADD AL, col adds the column index: 8 + 1 = 9. Since AH is already 0, AX = 0009h. The offset must be moved to an address register, because on the 8086 AL or AX cannot be used in addressing; only BX, SI, DI, and BP can be inside square brackets. With MOV SI, AX, SI = 0009h. The last instruction MOV DL, mat[SI] computes the effective address as 0112h + 9 = 011Bh and reads the byte there: DL = 32h.
| Line | AX | BL | SI | DL | Explanation |
|---|---|---|---|---|---|
3 MOV AL, row | 0002h | 00h | 0000h | 00h | row index |
4 MOV BL, NCOLS | 0002h | 04h | 0000h | 00h | constant embedded in the instruction |
5 MUL BL | 0008h | 04h | 0000h | 00h | 2 × 4: start of the row |
6 ADD AL, col | 0009h | 04h | 0000h | 00h | + column |
7 MOV SI, AX | 0009h | 04h | 0009h | 00h | offset in the index register |
8 MOV DL, mat[SI] | 0009h | 04h | 0009h | 32h | [0112h + 9] = [011Bh] |
MUL BL: row 2 starts at byte 8 of the table. On the right, MOV DL, mat[SI]: byte 9 is read, DL = 32h.Because the row and column are read from variables at run time, the same code works for every element of the table. In a word table the final offset would also be multiplied by 2; adding SHL SI, 1 is enough for that.
The constant was deliberately named NCOLS. Had COL EQU 4 been written, this name would have collided with col DB 1, because the assembler is case-insensitive. The assembler reports a “symbol defined twice” error and stops assembly.
4.2.4Addresses
A variable is associated with two numbers: the value stored in it and its place in memory, that is, its address. In assembly, when a variable's name is written alone in an instruction, it stands for its value. MOV AL, VAR1 brings the byte at VAR1's address into AL. Sometimes, however, the address itself is needed, not the value. Scanning an array with a pointer, telling a print service where a string is, or giving a procedure a large block of data without copying it are examples. This section describes two ways to put an address into a register: the LEA instruction and the OFFSET operator.
4.2.4.1Getting a variable's address
LEA (load effective address) is a processor instruction: it computes the effective address (relative location) of a memory operand and loads it into the destination register. It does not access memory. LEA BX, VAR1 loads the address of VAR1 into BX, and LEA BX, a[SI] loads the sum a + SI.
OFFSET is an assembler operator: it gives the relative location of a variable as a constant number at assembly time. MOV BX, OFFSET VAR1 is, in the assembler's eyes, an immediate load such as MOV BX, 010Dh.
LEA BX, VAR1 loads the address (010Dh), MOV AL, VAR1 the value (22h).| Instruction | Loaded into BX | Memory access |
|---|---|---|
MOV BX, VAR1 | the value of VAR1 (contents) | yes: two bytes are read |
LEA BX, VAR1 | the address of VAR1 | no: computed in the EU only |
MOV BX, OFFSET VAR1 | the address of VAR1 | no: the address is inside the instruction |
A variable's address is very handy for passing a parameter to a procedure. Copying the array itself to a subroutine that will process a thousand-byte array is both slow and wasteful of space. Instead only the 16-bit address is passed, for example in SI; the subroutine reaches the array through this address. DOS's string-printing service uses the same idea: the address of the string is expected in DX.
4.2.4.2Code trace: updating a variable with LEA
ORG 100h
MOV AL, VAR1 ; value
LEA BX, VAR1 ; address
MOV BYTE PTR [BX], 44h
MOV AL, VAR1 ; new value
RET
VAR1 DB 22h
ENDThe program's byte image is: A0 0D 01 (3), BB 0D 01 (3), C6 07 44 (3), A0 0D 01 (3), and C3 (1). The code is 13 bytes and RET is at 010Ch; VAR1 lands at address 0100h + 13 = 010Dh. emu8086 translates LEA BX, VAR1, which contains no base or index register, into the same three-byte code as MOV BX, OFFSET VAR1: the opcode BB and the 16-bit address. MASM, the real 8086 assembler, encodes the same line as a four-byte LEA in the form 8D 1E 0D 01.
MOV AL, VAR1 reads the value of VAR1: AL = 22h. LEA BX, VAR1, on the other hand, loads the address of VAR1 into BX: BX = 010Dh. BX is now a pointer to VAR1. MOV BYTE PTR [BX], 44h writes through this pointer. Because [BX] is a typeless memory operand, BYTE PTR is mandatory. The instruction writes 44h to DS:010Dh. The MOV AL, VAR1 on the last line reads the variable by name again and sees the new value: AL = 44h. The same memory location has been accessed both by name and through a pointer. END is the directive that marks the end of the source file and produces no bytes.
| Line | AL | BX | [010Dh] | Explanation |
|---|---|---|---|---|
2 MOV AL, VAR1 | 22h | 0000h | 22h | value is read |
3 LEA BX, VAR1 | 22h | 010Dh | 22h | address is loaded, memory is not read |
4 MOV BYTE PTR [BX], 44h | 22h | 010Dh | 44h | write through the pointer |
5 MOV AL, VAR1 | 44h | 010Dh | 44h | new value is read |
LEA BX, VAR1, BX = 010Dh and memory holds 22h. On the right, after MOV BYTE PTR [BX], 44h, VAR1 = 44h.In terms of hardware, the difference between LEA and MOV is in the bus cycle. In MOV AL, VAR1 the EU gives the address to the BIU, the BIU performs a read bus cycle, and the byte that arrives is written to AL. In LEA BX, VAR1 there is no read bus cycle: emu8086 puts the address into the instruction as a constant and the EU writes it directly to BX; this form takes 4 periods. In a LEA with a register (LEA BX, a[SI]) the EU computes the address at run time but does not send the result to the BIU, again writing it directly to the register; its time is 2 clock periods plus the effective address calculation.
4.2.4.3Are LEA and OFFSET the same?
The same program can also be written with OFFSET instead of LEA:
ORG 100h
MOV AL, VAR1
MOV BX, OFFSET VAR1
MOV BYTE PTR [BX], 44h
MOV AL, VAR1
RET
VAR1 DB 22h
ENDThe result is the same: BX takes the variable's address, the variable becomes 44h, and AL finally reads 44h. MOV BX, OFFSET VAR1 is an ordinary immediate load: BB 0D 01, three bytes. emu8086 translates the line LEA BX, VAR1 into exactly this code too; the bytes of the two programs are identical and VAR1 is at 010Dh in both. For a simple variable there is no difference between the two notations. In MASM, however, LEA BX, VAR1 is encoded as a four-byte real LEA instruction (8D 1E 0D 01).
The real difference appears with indexed addresses. OFFSET works at assembly time; it can give only constant addresses known to the assembler. OFFSET a[SI] is meaningless, because the value of SI is not known at assembly time. LEA BX, a[SI], on the other hand, computes the address at run time with SI's value at that moment. More complex expressions such as LEA SI, [BX+DI+4] are also possible; LEA works here like a small adder that does not change the flags.
LEA BX, VAR1 | MOV BX, OFFSET VAR1 | |
|---|---|---|
| When is it computed? | for an indexed address at run time, in the EU | at assembly time, in the assembler |
| Machine code (emu8086) | direct address: BB imm16 (3 bytes); indexed: 8D ModR/M (+ displacement) | BB imm16 (3 bytes) |
| Time (8086) | direct address: 4 periods; indexed: 2 + EA | 4 periods |
| Indexed address | possible: LEA BX, a[SI] | not possible |
| Flags | unchanged | unchanged |
For a constant address, MOV ... OFFSET is both short and fast. When an indexed address has to be computed, LEA is used. Whichever is chosen, only BX, SI, DI, and BP can appear inside square brackets.
4.2.4.4Code trace: LEA a[BX] and OFFSET a
ORG 100h
MOV BX, 2
LEA SI, a[BX] ; SI = a + BX
MOV DI, OFFSET a ; fixed address
ADD DI, BX ; add by hand
MOV AL, [SI]
INC BX
LEA SI, a[BX] ; new address
MOV AH, [SI]
RET
a DB 'ABCD'The code is 22 bytes; the array a starts at 0116h and holds the bytes 'A' 'B' 'C' 'D' (41h–44h). MOV BX, 2 prepares the index. LEA SI, a[BX] (8D B7 16 01) computes the address at run time: 0116h + 2 = 0118h. Memory is not read; SI only receives the address of 'C'.
MOV DI, OFFSET a (BF 16 01) loads the constant known at assembly time: DI = 0116h. This constant cannot include BX. A separate addition is needed to reach the same address: with ADD DI, BX, DI = 0118h = SI. The two ways gave the same address; LEA did it in a single instruction.
MOV AL, [SI] reads the byte at 0118h: AL = 43h ('C'). INC BX makes the index 3. The second LEA SI, a[BX] produces the new result with the same machine code: 0116h + 3 = 0119h. The instruction did not change; the address changed because BX changed. MOV AH, [SI] makes AH = 44h ('D'); AX = 4443h. DI stays at 0118h, because the value that came from OFFSET does not follow the change in BX.
| Line | BX | SI | DI | AX |
|---|---|---|---|---|
2 MOV BX, 2 | 0002h | 0000h | 0000h | 0000h |
3 LEA SI, a[BX] | 0002h | 0118h | 0000h | 0000h |
4 MOV DI, OFFSET a | 0002h | 0118h | 0116h | 0000h |
5 ADD DI, BX | 0002h | 0118h | 0118h | 0000h |
6 MOV AL, [SI] | 0002h | 0118h | 0118h | 0043h |
7 INC BX | 0003h | 0118h | 0118h | 0043h |
8 LEA SI, a[BX] | 0003h | 0119h | 0118h | 0043h |
9 MOV AH, [SI] | 0003h | 0119h | 0118h | 4443h |
LEA SI, a[BX]: SI = 0116h + 2 = 0118h. On the right MOV DI, OFFSET a: DI = 0116h, a fixed address unaware of BX.4.2.4.5Pointer variables
An address can be stored not only in a register but also in memory. If the value of a DW is a variable name, the assembler writes the address of that variable to memory.
A pointer variable is a variable that stores the address of another variable. p DW arr defines a 16-bit near pointer, and far_p DD arr a 32-bit far pointer made of an offset and a segment.
ORG 100h
MOV BX, p ; 010Bh
LEA SI, p ; 010Fh
MOV DI, OFFSET arr
RET
arr DB 'KAYA' ; 010Bh
p DW arr ; 010Fh, holds 010Bh
far_p DD arr ; offset + segmentThe code takes 11 bytes (8B 1E 0F 01, BE 0F 01, BF 0B 01, C3; emu8086 translates the line LEA SI, p into three bytes like MOV SI, OFFSET p). arr starts at 010Bh and occupies four bytes; p is at 010Fh and holds 010Bh, that is, the bytes 0B 01. far_p is at 0111h and takes four bytes: first the offset (0B 01), then the segment value. In emu8086's load segment these bytes are 0B 01 00 07.
| Instruction | What is loaded into the register? | Value |
|---|---|---|
MOV BX, p | the address inside p (the address of the array) | 010Bh |
LEA SI, p | p's own address | 010Fh |
MOV DI, OFFSET arr | the address of the array, a constant at assembly time | 010Bh |
The first and third rows in Table 4.2.19 give the same number but by different routes. MOV DI, OFFSET arr takes the number from inside the instruction and does not change. MOV BX, p, on the other hand, reads the number from memory. Because p sits in memory, the program can change it: ADD p, 2 moves the pointer two bytes further into the array. To use a pointer, it must first be taken into an address register, because the 8086 cannot read memory directly with an address that is in memory: MOV BX, p · MOV AL, [BX].
A far pointer is used to point at data in a different segment. The two words in it are loaded in one go with the LDS or LES instructions. LDS SI, far_p writes the low word to SI and the high word to DS; LES DI, far_p does the same job for DI and ES. Since far_p holds the bytes 0B 01 00 07, after LDS SI, far_p SI = 010Bh and DS = 0700h; then MOV AL, [SI] reads 'K' (4Bh).
4.2.4.6Code trace: a pointer in memory
ORG 100h
MOV BX, p ; contents of p
MOV AL, [BX] ; arr[0]
ADD p, 2 ; advance
MOV BX, p
MOV AH, [BX] ; arr[2]
RET
arr DB 'KAYA'
p DW arr ; addressThe code is 18 bytes; arr is at 0112h and p at 0116h with the initial value 0112h. MOV BX, p reads the contents of p: BX = 0112h. MOV AL, [BX] takes the byte the pointer points to: AL = 4Bh ('K'). ADD p, 2 is an addition that writes directly to memory. Because the constant is small, the assembler chooses the 5-byte form 83 06 16 01 02; the opcode 83h sign-extends the 8-bit constant to 16 bits. The processor first reads p, adds 2, and writes the result back. This instruction needs one read and one write bus cycle. p is now 0114h. BX, on the other hand, keeps holding the old address; the register and the pointer in memory are independent of each other.
MOV BX, p reloads the pointer: BX = 0114h. MOV AH, [BX] makes AH = 59h ('Y'); AX = 594Bh.
| Line | BX | AX | p |
|---|---|---|---|
2 MOV BX, p | 0112h | 0000h | 0112h |
3 MOV AL, [BX] | 0112h | 004Bh | 0112h |
4 ADD p, 2 | 0112h | 004Bh | 0114h |
5 MOV BX, p | 0114h | 004Bh | 0114h |
6 MOV AH, [BX] | 0114h | 594Bh | 0114h |
MOV AL, [BX]: the 'K' that the pointer points to is read. On the right ADD p, 2: the pointer in memory points to 0114h; BX stays at the old address.The address of the array was never written in the code; the pointer in memory decided which element would be read. On the 8086, which has few registers, this is the way to keep the locations of many arrays. At each use the pointer is first taken into BX, SI, or DI.
Confusing the value with the address. MOV SI, arr loads not the address of the array but its first word (if arr is DB, it gives a size error). For the address, write LEA SI, arr or MOV SI, OFFSET arr. For a pointer variable the reverse holds: MOV SI, p gives the address, and LEA SI, p the pointer's own location.
4.2.5Constants
Numbers that do not change are common in programs: the number of characters in a row, the number of columns of a table, the number of a port. Writing these numbers by hand at every place they occur creates two problems. The code becomes unreadable, because it is not clear what 80 means. If the value changes, all its uses have to be found and fixed, and it is easy to miss one. Keeping the number in a variable solves these problems but takes space in memory and requires a memory read at every use. Constants solve both problems at no cost.
4.2.5.1Defining a constant with EQU
A constant is a name defined in the form name EQU expression that exists only during assembly. At every use the assembler replaces the name with the value of the expression. A constant occupies no memory and cannot be changed after it is defined.
k EQU 5
ROWLEN EQU 80
MOV AX, k ; AX = 5
MOV BX, ROWLEN*2 ; BX = 160
MOV CL, k+1 ; CL = 6Constants carry a name similar to variables, but live only in the assembler's symbol table. When the assembler sees the line MOV AX, k, it encodes it as MOV AX, 5: B8 05 00. A constant's name, like a variable name, is case-insensitive and cannot collide with another name. An expression can also be given: ROWLEN*2 is computed as 160 at assembly time and 160 is embedded in the instruction. If the same value is used in different places in the program, the value is updated from a single place, the EQU line.
k EQU 5 | k DB 5 | |
|---|---|---|
| Memory | uses none | 1 byte |
MOV AL, k | AL ← 5 (immediate value, B0 05) | AL ← [k] (from memory, A0 + address) |
| Can it be changed? | no: MOV k, 7 is an error | yes: MOV k, 7 |
| When does it exist? | at assembly time only | at run time, in memory |
The line MOV k, 7 gives an error with an EQU constant. When the assembler replaces k with 5, the result is MOV 5, 7, and a number as a destination is meaningless. With a variable the same line is valid, because k points to a memory location.
4.2.5.2Code trace: EQU is embedded in the instruction
k EQU 5
ROWLEN EQU 80
ORG 100h
MOV AX, k ; MOV AX, 5
MOV BX, ROWLEN*2 ; MOV BX, 160
MOV CL, k+1 ; MOV CL, 6
MOV DL, v ; from memory
RET
v DB 5 ; takes 1 byteThe first two lines write k = 5 and ROWLEN = 80 into the symbol table; neither produces a byte. The first byte after ORG 100h is therefore directly the code of MOV AX, k. The program's byte image is B8 05 00 · BB A0 00 · B1 06 · 8A 16 0D 01 · C3 · 05. The code takes 13 bytes and v lands at 010Dh.
| Address | Machine code | Instruction | AX | BX | CL | DL |
|---|---|---|---|---|---|---|
| 0100h | B8 05 00 | MOV AX, 5 | 0005h | 0000h | 00h | 00h |
| 0103h | BB A0 00 | MOV BX, 160 | 0005h | 00A0h | 00h | 00h |
| 0106h | B1 06 | MOV CL, 6 | 0005h | 00A0h | 06h | 00h |
| 0108h | 8A 16 0D 01 | MOV DL, [010Dh] | 0005h | 00A0h | 06h | 05h |
MOV AX, k: the constant 5 is inside the instruction (B8 05 00). On the right MOV DL, v: the instruction carries the address of v (010Dh) and the value is read from memory.In the first three instructions the value is in the instruction's own bytes. Since 160 = 00A0h, BB A0 00 is written; k+1 = 6 is also computed at assembly time and becomes the single-byte B1 06. The processor does no addition or multiplication while running. The immediate value enters the prefetch queue along with the instruction. The EU takes it from the queue and no separate data bus cycle is needed. Loading an immediate value into a register takes 4 clock periods on the 8086.
The fourth instruction is different. v is a variable; the instruction carries not the value but the address (0D 01). The EU supplies the effective address, the BIU performs a read bus cycle from DS:010Dh, and DL = 05h. This instruction takes 8 + 6 = 14 periods. v occupies one byte in memory; k and ROWLEN occupy none.
In MASM and emu8086 the = directive also defines a constant: count = 3. The difference is that a name defined with = can be redefined later in the source. This suits names used as counters at assembly time. While the program runs, neither occupies memory and neither can be changed.
4.2.5.3The location counter and size operators
The location counter is the counter in which the assembler keeps the relative location of the next byte, and it is read in the source with $. $ gives its value on the line where it is used. This is the way to find the size of an array without counting by hand.
s DB 'Welcome', 0
n EQU $ - s ; 8
w DW 10 DUP(0)When the definition of s ends, the location counter points to the address one past the last byte of the string. $ - s is the difference of the two addresses, that is, the number of bytes of the string: 7 letters + 1 terminator = 8. This difference is assigned to an EQU constant and becomes an assembly-time constant. If the string is changed, n takes the new length automatically. It is essential that the EQU line come right after the array. If another definition comes in between, its bytes are counted too and n comes out wrong.
MASM also offers operators that read the same information from a variable's definition. TYPE gives the byte size of an element, LENGTHOF the number of elements, and SIZEOF the total number of bytes (in older MASM versions and in emu8086, LENGTH and SIZE).
| Expression | Value | Meaning |
|---|---|---|
n | 8 | number of bytes of s |
TYPE s | 1 | element size (DB) |
LENGTHOF s | 8 | number of elements |
TYPE w | 2 | element size (DW) |
LENGTHOF w | 10 | number of elements |
SIZEOF w | 20 | LENGTHOF × TYPE |
All these expressions are assembly-time constants. MOV CX, LENGTHOF w embeds the number 10 in the instruction and is encoded as B9 0A 00; it takes no extra space in memory. In a word array, LENGTHOF is used for a loop counter and SIZEOF for the length in bytes. In a byte array the two are the same.
4.2.5.4Code trace: the largest element using the array's size
ORG 100h
JMP start
arr DB 12, 47, 5, 31
n EQU $ - arr ; 4
big DB ?
start:
MOV CX, n ; CX = 4
MOV SI, 0
MOV AL, arr[SI] ; first guess
check:
CMP AL, arr[SI]
JAE skip ; AL >= element
MOV AL, arr[SI] ; new guess
skip:
INC SI
LOOP check
MOV big, AL
RETIn this program the data are at the start. The two-byte JMP start (EB 05) at 0100h skips the data. arr occupies 0102h–0105h and big 0106h; the code continues from 0107h. The line n EQU $ - arr is right after the array: at that point $ = 0106h and the difference is 0106h − 0102h = 4. MOV CX, n is therefore encoded as B9 04 00.
The algorithm rests on the idea of “the largest so far.” AL starts with the first element and becomes the guess. On each iteration the guess is compared with the next element. If the guess is smaller, the element becomes the new guess. CMP AL, arr[SI] performs AL − element and only sets the flags. JAE (jump if above or equal) compares as unsigned: it jumps if CF = 0, that is, if AL ≥ element. LOOP check decrements CX by one and returns to check if CX is not zero. LOOP and INC do not change CF; the CF in the table is the result of the last CMP.
| Round | Comparison | CF | JAE | AL | SI | CX |
|---|---|---|---|---|---|---|
| initial | — | 0 | — | 0Ch (12) | 0000h | 0004h |
| 1 | 12 − 12 | 0 | taken | 0Ch (12) | 0001h | 0003h |
| 2 | 12 − 47 | 1 | not taken | 2Fh (47) | 0002h | 0002h |
| 3 | 47 − 5 | 0 | taken | 2Fh (47) | 0003h | 0001h |
| 4 | 47 − 31 | 0 | taken | 2Fh (47) | 0004h | 0000h |
JAE is not taken and AL = 47 (2Fh). On the right, MOV big, AL after the loop: the largest element is written to memory.After the fourth round CX = 0 and LOOP falls through. MOV big, AL writes the result to 0106h: big = 2Fh = 47. The loop count was written by hand nowhere. If an element were added to the array, n would become 5 and the code would run five rounds unchanged. The comparison is unsigned, because the values in the array are assumed to be in the range 0–255. Had the array contained negative numbers, the signed JGE would have been used instead of JAE; otherwise −1 (FFh) would have been picked as the largest number.
4.2.6Example programs
All the rules about variables come together in small programs of a few lines. The programs in this section are based on emu8086's sample programs. Each does a basic job: moving data between variables, arithmetic, comparison, or multiword values. After each program, a trace table gives the registers, flags, and variables at every step.
4.2.6.1Moving data between variables
ORG 100h
jmp start
value1 DW 10 ; a 2-byte variable
value2 DW 0 ; a second one
start:
MOV AX, value1 ; AX ← value1
MOV value2, AX ; value2 ← AX
RET
end startThe program uses the layout that puts the data first. The jmp start at 0100h is a two-byte short jump (EB 04): the number 04 is the displacement to be added to the address of the instruction after the jump (0102h). The target is 0102h + 4 = 0106h. The four bytes in between are the variables: value1 at 0102h (0A 00) and value2 at 0104h (00 00). The jmp makes the processor jump over the data. Had there been no jump, the bytes 0A 00 would have been executed as the instruction OR AL, [BX+SI].
Since the 8086 has no memory-to-memory MOV, the move is done in two steps. MOV AX, value1 (A1 02 01) takes the value into AX: AX = 000Ah. MOV value2, AX (A3 04 01) writes AX to memory: 0104h now holds 0A 00. Both instructions are the short forms specific to AX and take 10 clock periods. This is also why AX was chosen as the intermediate register. The end start on the last line declares the end of the source and says that the program's entry point is the label start.
| Line | IP | AX | value1 (0102h) | value2 (0104h) |
|---|---|---|---|---|
2 jmp start | 0106h | 0000h | 000Ah (0A 00) | 0000h (00 00) |
6 MOV AX, value1 | 0109h | 000Ah | 000Ah | 0000h |
7 MOV value2, AX | 010Ch | 000Ah | 000Ah | 000Ah (0A 00) |
MOV AX, value1: AX = 000Ah. On the right MOV value2, AX: the bytes of value2 become 0A 00; now value1 = value2 = 10.The program begins with ORG 100h and ends with RET. Since ORG produces no bytes, the addresses do not change: jmp start is still at 0100h. After MOV value2, AX, the RET at 010Ch hands control back to DOS. Without this line the processor would have continued executing the bytes after 010Ch as instructions.
4.2.6.2Adding variables
ORG 100h
jmp start
value1 DW 105h ; initially 105h
value2 DW 103h ; initially 103h
result DW ? ; undefined
start:
MOV AX, value1 ; AX ← value1
ADD AX, value2 ; AX ← AX + value2
MOV result, AX ; result ← AX
RET
end startThe three variables are at 0102h, 0104h, and 0106h; this time jmp start skips six bytes (EB 06). result is defined with ?. emu8086 puts 00 00 in these bytes but its value is not to be relied on; the program writes it before reading it.
MOV AX, value1 makes AX = 0105h. ADD AX, value2 (03 06 04 01), unlike MOV, can use the memory operand directly: it adds AX and the word at [0104h]. The BIU reads the word, the ALU adds, and the result is written to AX. The instruction takes 9 + 6 = 15 clock periods. The sum can be done digit by digit: 5 + 3 = 8, 0 + 0 = 0, 1 + 1 = 2; there is no carry in any digit and AX = 0208h. Decimal check: 261 + 259 = 520 = 208h.
ADD sets all six status flags according to the result. Since no carry comes out of the top bit, CF = 0. The result is nonzero, ZF = 0. The top bit is 0, SF = 0. Since the sum of two positive numbers stays positive, there is no signed overflow, OF = 0. In the low nibble 5 + 3 = 8 and no carry passes from bit 3 to bit 4, AF = 0. The parity flag looks only at the low byte of the result: 08h = 0000 1000 has an odd number (one) of 1s, so PF = 0.
| Line | AX | CF | ZF | SF | OF | PF | AF | result (0106h) |
|---|---|---|---|---|---|---|---|---|
| initial | 0000h | 0 | 0 | 0 | 0 | 0 | 0 | 00 00 |
7 MOV AX, value1 | 0105h | 0 | 0 | 0 | 0 | 0 | 0 | 00 00 |
8 ADD AX, value2 | 0208h | 0 | 0 | 0 | 0 | 0 | 0 | 00 00 |
9 MOV result, AX | 0208h | 0 | 0 | 0 | 0 | 0 | 0 | 08 02 |
ADD AX, value2: 0105h + 0103h = 0208h, all flags 0. On the right MOV result, AX: little-endian 08 02 in memory.Had the sum not fit in a word, CF = 1. For example, with value1 = 0F000h and value2 = 2000h, 0F000h + 2000h = 11000h; only 1000h fits in AX and the 1 that spills out goes to CF. A program that checks for overflow looks at CF with JNC right after the ADD:
MOV AX, v1
ADD AX, v2
MOV v3, AX
JNC done
MOV overflow, 1
done:Since MOV v3, AX does not change the flags, JNC still sees the CF of the addition. For 105h + 103h, CF = 0 and overflow stays 0; for 0F000h + 2000h, v3 = 1000h and overflow = 1.
4.2.6.3Comparing two variables
ORG 100h
MOV AX, value1 ; AX ← value1
CMP AX, value2 ; AX − value2
JGE greater_or_equal
MOV AX, value2 ; if less, value2
JMP store_max
greater_or_equal:
MOV AX, value1
store_max:
MOV max_value, AX ; store result
RET
value1 DW 10
value2 DW 5
max_value DW ?The program writes the larger of two numbers to max_value. The code is in 0100h–0114h; value1 is at 0115h, value2 at 0117h, and max_value at 0119h. In this layout the data come after the RET.
CMP (compare) subtracts but does not store the result; it only sets the flags. CMP AX, value2 computes 000Ah − 0005h = 0005h: CF = 0, ZF = 0, SF = 0, OF = 0. AX does not change. JGE (jump if greater or equal) looks at the result of the signed comparison and jumps if SF = OF. Here SF = OF = 0, so it jumps and goes to greater_or_equal. The machine code of JGE is 7D 05: the target is found by adding 5 to the address of the next instruction, 0109h, giving 010Eh.
The MOV AX, value1 at the jump target makes AX 000Ah again. Since AX already holds value1, this line is redundant but harmless. MOV max_value, AX writes the result to 0119h: 0A 00. RET hands control back to DOS.
| Line | AX | CF | ZF | SF | OF | max_value | Explanation |
|---|---|---|---|---|---|---|---|
2 MOV AX, value1 | 000Ah | 0 | 0 | 0 | 0 | 0000h | |
3 CMP AX, value2 | 000Ah | 0 | 0 | 0 | 0 | 0000h | 10 − 5 = 5, result discarded |
4 JGE ... | 000Ah | 0 | 0 | 0 | 0 | 0000h | SF = OF: taken |
8 MOV AX, value1 | 000Ah | 0 | 0 | 0 | 0 | 0000h | redundant line |
10 MOV max_value, AX | 000Ah | 0 | 0 | 0 | 0 | 000Ah | 0A 00 in memory |
JGE: it is taken because SF = OF. On the right MOV max_value, AX: the larger value, 10 (000Ah), is written to memory.4.2.6.4Comparison: the other path
To see the program's other branch, the values of the variables are changed:
value1 DW 3
value2 DW 7
max_value DW ?The rest of the code is the same; the addresses do not change either. MOV AX, value1 makes AX = 0003h. CMP AX, value2 computes 0003h − 0007h. In the unsigned view 7 cannot be subtracted from 3 and a borrow is needed: CF = 1. The 16-bit result is FFFCh, that is, −4; since the top bit is 1, SF = 1. There is no signed overflow, because 3 − 7 = −4 is within the range: OF = 0. In the low nibble 3 − 7 also needs a borrow, AF = 1. The low byte of the result, FCh = 1111 1100, has six 1s, PF = 1.
This time SF = 1, OF = 0, and since SF ≠ OF, JGE is not taken. The processor moves on to the next instruction: MOV AX, value2 makes AX = 0007h. JMP store_max jumps unconditionally and skips the greater_or_equal branch. MOV max_value, AX writes 0007h. Whichever of the two branches the program goes through, it joins again at store_max.
| Line | AX | CF | ZF | SF | OF | max_value | Explanation |
|---|---|---|---|---|---|---|---|
2 MOV AX, value1 | 0003h | 0 | 0 | 0 | 0 | 0000h | |
3 CMP AX, value2 | 0003h | 1 | 0 | 1 | 0 | 0000h | 3 − 7 = FFFCh, discarded |
4 JGE ... | 0003h | 1 | 0 | 1 | 0 | 0000h | SF ≠ OF: not taken |
5 MOV AX, value2 | 0007h | 1 | 0 | 1 | 0 | 0000h | the larger one |
6 JMP store_max | 0007h | 1 | 0 | 1 | 0 | 0000h | unconditional jump |
10 MOV max_value, AX | 0007h | 1 | 0 | 1 | 0 | 0007h | 07 00 in memory |
CMP AX, value2: CF = 1 and SF = 1 for 3 − 7. On the right, because JGE is not taken, MOV AX, value2 executes: AX = 0007h.4.2.6.5Signed and unsigned comparison
The jump instruction in the comparison program was deliberately chosen as JGE. The 8086 has two families of jumps. JGE, JG, JL, and JLE make a signed comparison and look at SF, OF, and ZF. JAE, JA, JB, and JBE make an unsigned comparison and look at CF and ZF. The same CMP sets the flags both families need; the programmer chooses the interpretation with the jump instruction.
Let value1 = −1 (FFFFh in memory) and value2 = 5. CMP AX, value2 computes FFFFh − 0005h = FFFAh: CF = 0 (as unsigned, 65,535 ≥ 5), SF = 1, OF = 0. Because SF ≠ OF, JGE is not taken and max_value = 0005h; this is correct in the signed view, since −1 < 5. Had JAE been written, it would have been taken because CF = 0 and max_value = FFFFh; this is correct in the unsigned view, since 65,535 > 5.
Figure 4.2.25 shows the place of the same pattern on two number lines. Which jump is right depends on what the variable represents. A value that can be negative, such as a temperature or a position, calls for a signed jump; a counter or an address calls for an unsigned one.
The RET at the end of the program is mandatory. The data definitions come right after the code. Without the RET, the processor would have executed the bytes 0A 00 05 00 … at 0115h as instructions. The solution is either to put a RET at the end of the code, or to move the data to the start and jump over it with jmp start. An improvement of the program is also possible: the MOV AX, value1 under greater_or_equal is redundant. JGE can jump directly to store_max and the program becomes one instruction shorter.
4.2.6.6A double-word variable
The 8086 is a 16-bit processor; it has no 32-bit register. Still, it may be necessary to work with numbers larger than 65,535. Such values are stored in memory as 4 bytes with DD. In the processor they are held in two 16-bit registers, by convention in the pair DX:AX: DX takes the high word and AX the low word.
org 100h
jmp start
mydouble dd 12345678h ; double word
mywords dw 5678h ; 2 separate words
dw 1234h
mybytes db 78h ; 4 separate bytes
db 56h
db 34h
db 12h
data dd 00010010001101000101011001111000b
start: ; load data into DX:AX
mov ax, word ptr data
mov dx, word ptr [data+2]
retThe four definitions in the program have exactly the same counterpart in memory. mydouble gives the value as a single double word; the assembler writes it in little-endian order as 78 56 34 12. mywords produces the same bytes with two words: first the low word 5678h (78 56), then the high word 1234h (34 12). mybytes writes the four bytes one by one. data gives the value in binary: groups of four bits 0001 0010 0011 0100 0101 0110 0111 1000, that is, 12345678h. For the assembler it does not matter in which base or in which pieces the number was written; what remains in memory is four bytes arranged in little-endian order.
4.2.6.7Code trace: loading 32 bits into DX:AX
mov ax, word ptr data ; data+0
mov dx, word ptr [data+2] ; data+2
ret
data dd 12345678hdata is of type DD; when used with a word register, the sizes do not match. word ptr tells the assembler that only two bytes will be read in this access. The code is 8 bytes; data is at 0108h. mov ax, word ptr data (A1 08 01) reads the bytes 78 56 at 0108h and 0109h: AX = 5678h. mov dx, word ptr [data+2] (8B 16 0A 01) reads the bytes 34 12 at 010Ah and 010Bh: DX = 1234h. The pair DX:AX now holds 1234:5678h, that is, the value 12345678h.
| Line | Addresses read | DX | AX |
|---|---|---|---|
1 mov ax, word ptr data | 0108h, 0109h (78 56) | 0000h | 5678h |
2 mov dx, word ptr [data+2] | 010Ah, 010Bh (34 12) | 1234h | 5678h |
Arithmetic on a 32-bit value is also done in two parts. To add 1 to the value data dd 0FFFFFFFFh, 1 is first added to the low word, and then the carry that spills out of the low word joins the high word:
ADD AX, 1 ; low word
ADC DX, 0 ; high word + carryInitially AX = FFFFh and DX = FFFFh. ADD AX, 1 makes AX = 0000h and CF = 1. ADC (add with carry) adds CF as well as the second operand: DX = FFFFh + 0 + 1 = 0000h. The result is DX:AX = 00000000h, and this last addition also produces CF = 1, because the 32-bit result overflowed too. If the same operation is done for 0001FFFFh, DX:AX = 00020000h. Had ADD DX, 0 been written instead of ADC on the second line, the carry would have been lost and the result would wrongly come out as 00010000h.
4.2.6.8Common mistakes with variables
Most mistakes made when working with variables are of the kind the assembler cannot catch: the program assembles, runs, and gives a wrong result. The list below collects the most frequent ones.
- Confusing the value with the address.
MOV SI, arrloads the first word; for the address,LEA SI, arrorMOV SI, OFFSET arris needed. - Moving from memory to memory. There is no
MOV v1, v2; the value goes through a register. The assembler catches this. - The index in a word array. The 3rd element is at
w[4]; the index is in bytes.w[1]combines the halves of two elements. - Relying on the
?value.total DW ?may not be zero;MOV total, 0is written before the summation starts. - Forgetting the suffix.
DW 10is decimal 10 (000Ah); for hexadecimal write10h. Hexadecimal numbers that begin with a letter get a leading 0:0FFh,0ABCDh. - Name collision.
COL EQU 4andcol DB 1are the same name; the assembler reports a “defined twice” error. - Putting data in the path of execution. If there is no
RETorJMP, the data bytes are taken for instructions. - Forgetting the terminator. Without a 0 or '$', printing continues with the bytes behind the string.
4.2.6.9Summary of data definition
| Notation | Meaning | Memory |
|---|---|---|
x DB 7 | one byte | 07 |
y DW 1234h | one word | 34 12 |
z DD 12345678h | double word | 78 56 34 12 |
s DB 'Hi', 0 | string + terminator | 48 69 00 |
t DB 3 DUP(0) | repetition | 00 00 00 |
u DW ? | no initial value | ?? ?? (emu8086: 00 00) |
k EQU 10 | constant | occupies no memory |
To get an address, write LEA BX, x or MOV BX, OFFSET x; to read the value, MOV AL, x. If the size of an access is to differ from the variable's type, byte ptr or word ptr is used.
4.2.7Summary
- A variable is a data area in memory bound to a name. The assembler replaces the name with a relative location; the running program has no name, only the address embedded in the instruction.
DB,DW, andDDreserve 1, 2, and 4 bytes respectively and give the variable the type BYTE, WORD, or DWORD.?reserves an area with no initial value; its value is not to be relied on.- Only the bit pattern is stored in memory. Whether the pattern is signed or unsigned is determined by the instruction that uses it: CF,
JAE,JBinterpret it as unsigned; OF,JGE,JL,CBWas signed. - The assembler does type checking: the size of the register and the variable must match. For typeless operands and for a deliberate size change,
BYTE PTR/WORD PTRis used.LABELgives a second name and type to the same address. - The 8086 is little-endian: the low byte of multi-byte values is at the low address. This rule applies to the addresses inside instructions too.
- With the location counter the assembler computes the relative location of every byte and turns names into addresses in two passes.
ORG 100hdeclares that a .COM program starts at 0100h, after the PSP; in .COM, CS = DS = ES = SS. - A word starting at an odd address is read in two bus cycles and costs 4 clock periods.
EVENaligns words to even addresses. - Data is written either after the
RETor behind aJMP; the processor takes data bytes in its path for instructions. In an .EXE program DS is loaded first. - An array is consecutive elements of the same type. The index is in bytes: in a word array the i-th element is at offset
2 × i.DUPrepeats value lists and can be nested. - Strings are defined with
DBand their end is marked by 0, '$', or a length byte. Upper and lower case differ only in bit 5; subtracting '0' from a digit character gives the number. - Two-dimensional arrays are stored in row-major order: offset = (row × number of columns + column) × element size.
LEAcomputes the effective address at run time and does not access memory;OFFSETgives a constant address at assembly time. An indexed address can be obtained only withLEA. Pointer variables store an address in memory.EQUconstants exist only at assembly time, are embedded in the instruction as immediate values, and occupy no memory.$ - arrcomputes the size of an array automatically.- There is no memory-to-memory move; the value goes through a register.
CMPsets the flags without storing the result. 32-bit values are held in the pair DX:AX and added with theADD/ADCpair.
4.2.8Key terms
- variable
- data definition (DB / DW / DD)
- initial value
- directive
- byte
- word
- double word
- signed / unsigned number
- two's complement
- sign extension
- byte ptr / word ptr
- little-endian
- offset
- location counter ($)
- .COM program
- program segment prefix (PSP)
- aligned / unaligned access
- bus cycle
- array
- string
- ASCII
- row-major order
- effective address (EA)
- OFFSET operator
- pointer variable
- constant (EQU)
- immediate value
- carry flag (CF)
- overflow flag (OF)
4.2.9Test Yourself
The definitions
p DB 'Az', 0·q DW 300·r DD 0Ahstart at 0300h. What are the address and value of each byte? How many bytes do the definitions occupy in total?Answer
0300h: 41h ('A'), 0301h: 7Ah ('z'), 0302h: 00h. Since 300 = 012Ch, 0303h: 2Ch, 0304h: 01h.
ris at 0305h–0308h: 0A 00 00 00. Total 3 + 2 + 4 = 9 bytes.How many bytes does
tab DW 5 DUP(4 DUP(?))occupy? In row-major order, what is the byte offset of the element [3][2] fromtab?Answer
5 × 4 = 20 words = 40 bytes. The offset is (3 × 4 + 2) × 2 = 28 = 1Ch. To read it,
MOV SI, 28·MOV AX, tab[SI]can be written.Right after the line
s DB 'Test', 13, 10, '$',n EQU $ - sis written. What isn? What would happen ift DB 0came in between?Answer
4 letters + CR + LF + '$' = 7. Had
t DB 0come in between,$would have advanced by one byte andn= 8; the constant would no longer give the size of the string.With BX = 0100h, DI = 0020h, and CF = 1,
LEA SI, [BX+DI+4]is executed. What does SI become? Does CF change? Is anything read from memory?Answer
SI = 0100h + 0020h + 4 = 0124h.
LEAdoes not change the flags; CF = 1 stays. Only the address is computed; no read bus cycle is made.With AL = 80h and BL = 7Fh,
CMP AL, BLis executed. What are CF, SF, and OF? IsJAtaken, and isJGtaken afterwards?Answer
80h − 7Fh = 01h. As unsigned, 128 ≥ 127, no borrow: CF = 0, ZF = 0,
JAis taken. As signed, −128 − 127 = −255 is out of range: OF = 1, and since the result is 01h, SF = 0. Because SF ≠ OF, the result is −128 < 127 andJGis not taken.w DW 0102h, 0304his defined. What are AX and BL afterMOV AX, w[2]andMOV BL, BYTE PTR w+1? Why doesMOV BL, w+1not assemble?Answer
w[2]is the second element: AX = 0304h. Since memory is 02 01 04 03, the byte atw+1is 01h: BL = 01h. Becausewis of type WORD,MOV BL, w+1gives a size mismatch;BYTE PTRis needed.MOV DX, OFFSET msgandLEA DX, msggive the same result. How many bytes is each and roughly how many clock periods does each take on the 8086? Which can be used for an indexed address?Answer
MOV DX, OFFSET msgis an immediate load: 3 bytes (BA + 16 bits), 4 periods. emu8086 translates the lineLEA DX, msginto the same code; both are 3 bytes and 4 periods (the real LEA in MASM, however, is 4 bytes, 8D 16 + 16 bits, and 2 + 6 = 8 periods). An indexed address (LEA DX, msg[SI]) can be obtained only with LEA.With DX:AX = 0001FFFEh,
ADD AX, 3·ADC DX, 0are executed to add 3. What are AX, DX, and CF after each instruction?Answer
ADD AX, 3: FFFEh + 3 = 10001h; AX = 0001h, CF = 1.ADC DX, 0: 0001h + 0 + 1 = 0002h, CF = 0. The result is DX:AX = 00020001h = 0001FFFEh + 3.With the location counter at 0105h,
a DB 1, 2·EVEN·w DW 5is written. At which address doeswland? Why wouldMOV AX, wbe slower withoutEVEN?Answer
aoccupies 0105h–0106h and the counter becomes 0107h.EVENputs a padding byte at 0107h andwlands at 0108h. WithoutEVEN,wwould be at 0107h, starting at an odd address. The word would be read in two bus cycles and the access would take 4 periods longer (14 instead of 10).
4.2.10Further reading
- The emu8086 documentation, 8086 assembler tutorial for beginners, chapter 3 (variables): DB, DW, arrays, DUP, LEA, OFFSET, and EQU are explained with the examples that are the starting point of the programs in these notes.
- Kip R. Irvine, Assembly Language for x86 Processors, the data-definition chapter: data directives, little-endian order,
$, and the TYPE, LENGTHOF, and SIZEOF operators are given with detailed examples. - Barry B. Brey, The Intel Microprocessors, the chapters on addressing modes and data-movement instructions: LEA, LDS/LES, and the machine code and hardware-level operation of direct addressing are covered.
- Microsoft, MASM 6.1 Programmer's Guide: the precise definitions and rules of the DB/DW/DD, DUP, EQU,
=, OFFSET, LABEL, and EVEN directives.
4.2.11References
- The emu8086 documentation, 8086 assembler tutorial for beginners, chapter 3: variables (DB, DW, DUP, LEA, OFFSET, EQU).
- Barry B. Brey, The Intel Microprocessors, 8th edition, Pearson.
- Kip R. Irvine, Assembly Language for x86 Processors, Pearson (data-definition directives).
- Microsoft, MASM 6.1 Programmer's Guide: DB/DW/DD, DUP, EQU, OFFSET.
- Intel, The 8086 Family User's Manual, 1979 (instruction encoding and clock-period counts).
Related pages: Chapter 4.2 slides · © Sercan Külcü. All rights reserved.