Microprocessors · Lecture Notes
Chapter 6: Arithmetic, Logic and Shift Instructions
The real job of a processor is to compute. In the 8086 this job is done by the arithmetic logic unit (ALU) inside the execution unit: it adds two numbers, subtracts one from the other, passes their bits through AND, OR and exclusive-OR gates, and shifts them left or right. At the end of every operation the ALU not only writes the result to a register or to memory; it also records how the result came out in the six status bits of the flags register. Later instructions, especially conditional jumps, make their decisions by looking at these bits. These notes take up the arithmetic and logic instructions of the 8086 one by one and show which flag each instruction changes and how. First the two readings, unsigned and signed, of the same bit pattern are explained, together with the difference between the carry and overflow flags. Then come addition, subtraction, comparison and the logic instructions, the implicit registers of multiplication and division, sign extension, the single-operand instructions, and shifts and rotates. How 32-bit addition, subtraction and multiplication are done on a 16-bit processor is traced step by step. The last parts examine array summation, binary-coded decimal (BCD) arithmetic and temperature conversion programs at register and flag level.
Learning outcomes
- Compute the flags
- Find the values of CF, ZF, SF, OF, PF and AF from the result of an addition or subtraction; separate the unsigned and signed readings of the same result and explain the difference between CF and OF.
- Use instructions with the right operands
- Know the valid operand forms of the two-operand, multiply-divide and single-operand instruction groups; say which flags each instruction changes, which it preserves and which it leaves undefined.
- Multiply and divide
- Use the implicit registers (AL, AX, DX:AX) of MUL, IMUL, DIV and IDIV; prepare the dividend before a division with CBW, CWD or by zeroing the upper half; recognize the causes of a divide error.
- Multiword arithmetic
- Do 32-bit addition and subtraction with ADC and SBB and a 32 × 32-bit multiplication with four MULs; trace how the carry is passed from word to word.
- Bit operations
- Clear, set, invert and test bits with AND, OR, XOR and TEST; trace the effect of shift and rotate instructions on CF; multiply and divide with shifts and additions.
- Trace application programs
- Trace array summation, BCD adjustment and temperature conversion programs step by step at register, memory and flag level; find the range of numbers for which a program is valid.
6.1Flags and the result of an operation
6.1.1Where does the ALU write its result?
The inside of the 8086 is divided into two units. The bus interface unit (BIU) fetches instruction bytes from memory, places them in the prefetch queue, and reads and writes memory operands. The execution unit (EU) decodes and executes the instruction it takes from the queue. All calculations such as addition, subtraction, AND, OR and shifts are done in the 16-bit arithmetic logic unit (ALU) inside the EU. The ALU has two inputs and one output. The inputs come from registers, from the immediate value in the instruction, or from a number the BIU fetched from memory. The output goes to the destination register or, through the BIU, to memory.
The ALU has a second output as well: a few bits that describe the properties of the result. Is the result zero, is its leftmost bit 1, did a carry come out of the leftmost bit? The yes/no answers to these questions are written to the status bits of the 16-bit flags register (FLAGS). Figure 6.1 shows the bit layout of the flags register. Nine of the sixteen bits are used. Six are status flags: CF, PF, AF, ZF, SF and OF describe the result of the last arithmetic or logic operation. Three are control flags: TF, IF and DF govern the behavior of the processor and arithmetic instructions do not touch them.
Flags are a bridge that carries information between instructions. The CMP AL, BL instruction compares two numbers but writes the result to no register; it only changes the flags. A conditional jump right after it, such as JZ, JC or JO, makes its decision by looking at these flags. In multiword addition, the carry of the first addition waits in CF and the second addition takes it up with ADC. So two questions are asked of every instruction: where does it write its result, and which flags does it change and how?
Table 6.1 collects the status and control flags, the condition under which each becomes 1, and a short example of each. A detailed description of each flag and how it is produced in hardware is given in the notes on the 8086 registers (Chapter 2.2). Here only the rules sufficient for computing the flags after an addition or subtraction are summarized.
| Bit | Flag | Type | Set to 1 if… | Example |
|---|---|---|---|---|
| 0 | CF (carry) | status | unsigned overflow: a carry out of the most significant bit in addition, a borrow in subtraction | FFh + 01h → AL = 00h, CF = 1; 7 − 9 → CF = 1 |
| 2 | PF (parity) | status | the low byte of the result has an even number of 1 bits | 96h = 1001 0110b → four 1s → PF = 1 |
| 4 | AF (auxiliary carry) | status | a carry or borrow from bit 3 to bit 4 | 08h + 08h = 10h → AF = 1 |
| 6 | ZF (zero) | status | all bits of the result are 0 | SUB AL, AL → ZF = 1 |
| 7 | SF (sign) | status | the most significant bit (MSB) of the result is 1 | 96h → SF = 1 |
| 8 | TF (trap) | control | INT 1 after every instruction (single step) | used by debuggers |
| 9 | IF (interrupt) | control | interrupts from the INTR pin are accepted | STI → 1, CLI → 0 |
| 10 | DF (direction) | control | string instructions decrement SI and DI | CLD → 0, STD → 1 |
| 11 | OF (overflow) | status | signed overflow: the result did not fit in the signed range | 100 + 50 → AL = 96h (−106), OF = 1 |
The hardware counterpart of the status flags is simple. The ALU's adder adds the bits from right to left with a chain of full adders. The carry that bit 7 produces in a byte operation, or bit 15 in a word operation, goes directly to CF. The carry that bit 3 produces goes to AF. SF is a copy of the most significant bit of the result. ZF is the output of a NOR gate that takes all the bits of the result as input. PF passes the eight bits of the low byte through an exclusive-OR tree and inverts the result; even for a word result it looks only at the low byte. OF is the exclusive-OR of the carry into the most significant bit and the carry out of that bit. This last rule is seen with numbers in the examples below.
In subtraction the ALU does not use a separate subtractor. It performs A − B by adding A + (the ones' complement of B) + 1; this is addition with a two's complement. A carry out of the leftmost bit in this addition actually means that no borrow was needed. The 8086 therefore inverts the carry in subtraction and writes it to CF. As a result, CF behaves in subtraction like a borrow flag: in the unsigned reading, CF = 1 if a larger number was subtracted from a smaller one.
6.1.2CF or OF?
The eight bits in a register are, by themselves, neither an unsigned nor a signed number. The sequence 1001 0110b means 150 if read as unsigned, and −106 if read as signed two's complement. The processor does the addition on the bits only and produces the same result for both readings. It is the programmer who knows which reading applies. The processor takes both readings into account and keeps two separate flags: CF says whether the result is correct in the unsigned reading, OF in the signed reading.
The carry flag (CF) shows that, when the operation is done with the unsigned reading, the result does not fit the size of the destination. CF = 1 if in byte addition the true sum exceeds 255, or in subtraction the result falls below 0.
The overflow flag (OF) shows that, when the operation is done with the signed two's complement reading, the result does not fit the range. For a byte the range is −128…127 and for a word it is −32,768…32,767. OF = 1 if the sum of two numbers of the same sign comes out with the opposite sign.
Table 6.2 puts five byte additions side by side with the two readings. In every row the result written to AL is one; the only thing that changes is how it is read.
| AL + operand | Unsigned reading | Signed reading | AL | CF | OF |
|---|---|---|---|---|---|
FFh + 01h | 255 + 1 = 256 | −1 + 1 = 0 | 00h | 1 | 0 |
64h + 32h | 100 + 50 = 150 | 100 + 50 = 150 | 96h | 0 | 1 |
C8h + 64h | 200 + 100 = 300 | −56 + 100 = 44 | 2Ch | 1 | 0 |
80h + 80h | 128 + 128 = 256 | −128 + (−128) = −256 | 00h | 1 | 1 |
05h + 0Ah | 5 + 10 = 15 | 5 + 10 = 15 | 0Fh | 0 | 0 |
In the first row the unsigned sum is 256 and does not fit in a byte. 256 − 256 = 0 stays in AL and the carry that comes out falls into CF. In the signed reading, however, −1 + 1 = 0 is entirely correct; OF = 0. This row shows that CF = 1 is not an error in signed arithmetic. The second row is the opposite. 150 fits in a byte as unsigned, CF = 0. But a signed byte can be at most 127; the sum of two positive numbers has come out 96h, and the sign bit of 96h is 1. In the signed reading this means −106 and is wrong: OF = 1.
In the third row the two readings again part ways. Unsigned 300 does not fit, CF = 1. In the signed reading, one of the numbers is negative (−56) and the other positive (100). The sum of two numbers with different signs is smaller than the larger of them in absolute value; so it can never fall outside the range. The result 44 is correct and OF = 0. In the fourth row both readings are wrong: 256 does not fit in a byte, and −256 does not fit either. Both flags are 1 together. In the last row both readings are correct and both flags are 0.
The rule for OF can also be stated in terms of the carries at the most significant bit. Let us add the second row bit by bit: 0110 0100b + 0011 0010b. At bit 5, 1 + 1 = 10b; 0 is written and a carry of 1 passes to bit 6. At bit 6, 1 + 0 + 1 = 10b; 0 is written and the carry enters bit 7. At bit 7, 0 + 0 + 1 = 1 is written and no carry goes out. The carry into bit 7 is 1 and the carry out is 0. Because the two differ, OF = 1. In the fourth row, no carry enters bit 7 at all but 1 + 1 produces a carry out: carry in 0, carry out 1, again OF = 1. In the first row a carry enters bit 7 and a carry also goes out: because the two are the same, OF = 0.
In addition, OF = (carry into the most significant bit) XOR (carry out of the most significant bit). In terms of signs this reads: if the sum of two numbers of the same sign comes out with the opposite sign, OF = 1; when two numbers of different signs are added, OF is never 1. In subtraction (A − B) the rule takes this form: if the difference of two numbers of different signs has a sign different from that of A, OF = 1.
Reading CF as "overflow" and looking at CF when working with signed numbers. In the addition −1 + 1, CF = 1, although the signed result is correct. A program that works with signed numbers looks at OF (and, in comparisons, at SF and OF); a program that works with unsigned numbers looks at CF. The processor does not know which one applies; the choice belongs to whoever writes the instructions.
6.1.3Code trace: CF, OF and the other flags
The following short program shows how flags carry over from one instruction to the next. The program starts with 9Ch; 9Ch is 156 in the unsigned reading and −100 in the signed reading. Then come two separate additions, then adding a number to itself, INC and CMC.
MOV AL, 9Ch ; 156 or -100
ADD AL, 70h ; + 112
MOV AL, 50h ; 80
ADD AL, 50h ; + 80
ADD AL, AL ; A0h + A0h
MOV AL, 0FFh
INC AL ; CF untouched
CMC ; flip CF
RET| Instruction | Machine code | AL | CF | OF | SF | ZF | AF | PF |
|---|---|---|---|---|---|---|---|---|
MOV AL, 9Ch | B0 9C | 9Ch | 0 | 0 | 0 | 0 | 0 | 0 |
ADD AL, 70h | 04 70 | 0Ch | 1 | 0 | 0 | 0 | 0 | 1 |
MOV AL, 50h | B0 50 | 50h | 1 | 0 | 0 | 0 | 0 | 1 |
ADD AL, 50h | 04 50 | A0h | 0 | 1 | 1 | 0 | 0 | 1 |
ADD AL, AL | 02 C0 | 40h | 1 | 1 | 0 | 0 | 0 | 0 |
MOV AL, 0FFh | B0 FF | FFh | 1 | 1 | 0 | 0 | 0 | 0 |
INC AL | FE C0 | 00h | 1 | 0 | 0 | 1 | 1 | 1 |
CMC | F5 | 00h | 0 | 0 | 0 | 1 | 1 | 1 |
In the first addition 156 + 112 = 268. 268 does not fit in a byte; 268 − 256 = 12 = 0Ch stays in AL and CF = 1. In the signed reading −100 + 112 = 12 is correct; because two numbers of different signs are added, OF cannot be 1 anyway. 0Ch = 0000 1100b has two 1s, so PF = 1. Since the low nibbles C + 0 = C, no carry comes out of bit 3: AF = 0.
The MOV in the third row changes no flag. This is a rule that is often forgotten: data movement instructions such as MOV, LEA and XCHG do not pass through the ALU, and the flags stay as whatever the previous arithmetic instruction left. CF = 1 and PF = 1 stay in place.
In the fourth row 80 + 80 = 160 is correct in the unsigned reading; CF = 0. But the sum of two positive numbers has come out A0h = 1010 0000b and the sign bit is 1. In the signed reading this is −96 and wrong: OF = 1, SF = 1. In the fifth row A0h is added to itself. Unsigned 160 + 160 = 320 does not fit, CF = 1. Signed −96 + (−96) = −192 does not fit either, OF = 1. The 40h left in AL is a wrong result in both readings.
The INC AL in the seventh row adds 1 to FFh and AL = 00h. Because the result is zero, ZF = 1, and because F + 1 in the low nibble gives a carry, AF = 1. If the same operation were done with ADD AL, 1, a carry would come out and CF = 1. INC, however, never touches CF; the CF = 1 in the table is left over from the addition in the fifth row. The CMC (complement carry) in the last row only inverts CF. In the same family STC sets CF to 1 and CLC sets CF to 0.
6.1.4The flags of ADD step by step
The most reliable way to compute flags by hand is to do the addition on paper in binary. The instructions MOV AL, 64h and ADD AL, 32h add 100 and 50. Figure 6.2 shows the two operands, the result, and from which bit each flag is read.
- Result. 0110 0100b + 0011 0010b = 1001 0110b = 96h. In the unsigned reading 150 is correct; in the signed reading −106 is wrong.
- CF. No carry came out of the leftmost bit; 150 ≤ 255. CF = 0.
- OF. The carry into bit 7 is 1, the carry out is 0. The sum of two positive numbers looked negative. OF = 1.
- SF and ZF. Bit 7 of the result is 1, SF = 1. The result is not zero, ZF = 0.
- PF. 1001 0110b has four 1s; four is even, PF = 1.
- AF. The low nibbles are 4 + 2 = 6; no carry passes from bit 3 to bit 4, AF = 0.
Result: AL = 96h; CF = 0, ZF = 0, SF = 1, OF = 1, PF = 1, AF = 0. When this calculation is run in emu8086, the same values are seen in the flags window. The flag calculator in the slides sets up the same table for other numbers and other instructions.
What are the flags after MOV AL, 0C0h and ADD AL, 0C0h?
C0h = 1100 0000b; 192 unsigned, −64 signed. The sum is 1 1000 0000b = 180h. 80h is written to AL and the carry that comes out falls into CF: CF = 1. The carry into bit 7 is 1 (from the 1 + 1 at bit 6) and the carry out is also 1; OF = 0. Indeed −64 + (−64) = −128 fits a signed byte exactly. SF = 1, ZF = 0. 80h has a single 1 bit: PF = 0. Since the low nibbles are 0 + 0, AF = 0.
6.2Instruction groups and operand rules
6.2.1Three groups
The arithmetic and logic instructions of the 8086 fall into three groups according to how they take their operands. This division eases memorization: instructions in the same group accept the same operand forms and are encoded similarly in machine code. Figure 6.3 shows the operand layout of the three groups side by side.
- Group 1, two-operand instructions: ADD, SUB, CMP, AND, TEST, OR, XOR. ADC (add with carry) and SBB (subtract with borrow) are also added to this list. The form is
instruction destination, source; the operation is done between the destination and the source and the result is written to the destination. - Group 2, multiplication and division: MUL, IMUL, DIV, IDIV. A single operand is written in the instruction. The other half of the operation and the place where the result goes are fixed: AL, AX or DX:AX. These are called implicit operands.
- Group 3, single-operand instructions: INC, DEC, NOT, NEG. The operand is both read and written:
INC CXreads CX, adds 1 and writes the result back to CX.
Table 6.4 summarizes what each instruction does in one line. Shifts and rotates also take a single operand, but because they give the shift count as a second operand they are treated as a separate family.
| Group | Instruction | What it does |
|---|---|---|
| 1 | ADD | adds two values, writes the result to the destination |
SUB | subtracts the source from the destination, writes the result to the destination | |
CMP | subtracts the source from the destination, does not store the result; only sets the flags | |
AND | bitwise AND | |
TEST | bitwise AND; does not store the result | |
OR | bitwise OR | |
XOR | bitwise exclusive OR | |
| 2 | MUL | unsigned multiplication |
IMUL | signed multiplication | |
DIV | unsigned division (quotient and remainder) | |
IDIV | signed division (quotient and remainder) | |
| 3 | INC | increments by 1 |
DEC | decrements by 1 | |
NOT | inverts all bits (ones' complement) | |
NEG | negates (two's complement) |
6.2.2Operands of two-operand instructions
All the instructions in group 1 accept the same five operand combinations. These are given with examples in Table 6.5. REG is one of the 8- or 16-bit general-purpose registers: AX, BX, CX, DX, AH, AL, BL, BH, CH, CL, DH, DL, SI, DI, BP, SP. Memory is a memory operand ([BX], [BX+SI+7], a variable name). Immediate is a value written inside the instruction (5, −24, 3Fh, 10001101b).
| Form | Example | Machine code |
|---|---|---|
| REG, memory | ADD AX, [BX] | 03 07 |
| memory, REG | SUB var1, CL | 28 0E + address |
| REG, REG | XOR AX, AX | 33 C0 |
| memory, immediate | AND BYTE PTR [SI], 0Fh | 80 24 0F |
| REG, immediate | CMP AL, 'A' | 3C 41 |
The rules resemble the rules of MOV and come from the same hardware constraint. Both operands cannot be in memory: ADD [BX], [SI] is invalid, because the ModR/M byte of the instruction can describe only a single memory address. The two operands must be the same size: ADD AL, BX tries to add a 16-bit number to an 8-bit register and the assembler rejects it. The destination cannot be a constant: ADD 5, AL could not know where to write the result. Segment registers cannot be arithmetic operands: ADD DS, AX is invalid; DS is changed only with MOV, PUSH and POP.
When a memory operand is used with a constant, the size cannot be told from either. In the form AND [SI], 0Fh, 0Fh could be a byte or a word; so BYTE PTR or WORD PTR must be specified. If one of the operands is a register or a variable of known type, the size is taken from it.
Trying to add two variables directly: ADD total, count. Both operands are in memory and this instruction does not exist. One of them is first moved into a register: MOV AX, count and ADD total, AX.
6.2.3Where is the result written, and how are the flags affected?
After a two-operand operation the result is always stored in the first operand, that is, the destination. The SUB AX, BX instruction computes AX − BX and writes it to AX; BX does not change. CMP and TEST are the two exceptions to this rule. CMP does the subtraction SUB does but discards the result. TEST does the bit-by-bit AND that AND does but discards the result. Both only change the flags and so make testing possible without spoiling a register.
The effect on the flags depends on whether the operation is arithmetic or logic. Table 6.6 compares the two families.
| Instruction | CF | ZF | SF | OF | PF | AF |
|---|---|---|---|---|---|---|
ADD, ADC, SUB, SBB, CMP | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
AND, OR, XOR, TEST | 0 | ✓ | ✓ | 0 | ✓ | ? |
Arithmetic instructions set all six status flags according to the result. Logic instructions have no notion of a carry: each bit is processed on its own and nothing passes from one bit to another. So CF and OF are always set to 0. ZF, SF and PF are set according to the result. The value of AF is left undefined in Intel's documents; a program must not rely on AF after a logic instruction. Undefined does not mean the flag is random; on a real processor it takes a definite value, but that value is promised in no document and may come out differently on another x86 processor.
6.2.4Timing: time inside the processor and on the bus
The time an instruction takes depends closely on where its operands are. Two numbers in registers go straight into the ALU; ADD AX, BX takes 3 clock cycles on the 8086. If there is a memory operand, the EU first computes the effective address and then asks the BIU for a read bus cycle. A bus cycle is at least 4 clock cycles: the address is put on the bus, memory is read, and the data is taken into the chip. If the destination is in memory, another bus cycle is needed to write the result back. During this read-modify-write, the 8086's RD pin becomes active first and the WR pin later. Table 6.7 gives the times from Intel's 8086 manual; EA is the time to compute the effective address (5–12 cycles).
| Form | ADD, ADC, SUB, SBB, AND, OR, XOR | CMP | TEST |
|---|---|---|---|
| reg, reg | 3 | 3 | 3 |
| reg, mem | 9 + EA | 9 + EA | 9 + EA |
| mem, reg | 16 + EA | 9 + EA | 9 + EA |
| reg, imm | 4 | 4 | 5 |
| mem, imm | 17 + EA | 10 + EA | 11 + EA |
| AL/AX, imm | 4 | 4 | 4 |
The differences in the table come from bus cycles. ADD [BX], AX both reads and writes memory and takes 16 + EA cycles. CMP [BX], AX does the same subtraction but, because it does not write the result, only reads: 9 + EA cycles. On a 5 MHz 8086 a clock cycle is 200 ns; ADD [BX], AX (EA = 5) takes about 21 × 200 ns = 4.2 µs. The same addition between two registers takes 0.6 µs. This is the reason for keeping frequently used values in registers throughout a loop.
6.3Addition, subtraction and comparison
6.3.1Code trace: ADD, SUB, CMP
The following program does an addition, a subtraction and two comparisons; the last line completes a negative number to zero. The flag effect of each instruction is traced together with the bit-level detail of the operation.
mov al, 0F0h ; 240
add al, 20h ; 240 + 32 = 272
mov bl, 7
sub bl, 9 ; 7 - 9
cmp al, 10h ; AL - 10h
cmp bl, 0
add bl, 2 ; FEh + 2| Instruction | Machine code | AL | BL | CF | ZF | SF | OF | PF | AF |
|---|---|---|---|---|---|---|---|---|---|
mov al, 0F0h | B0 F0 | F0h | 00h | 0 | 0 | 0 | 0 | 0 | 0 |
add al, 20h | 04 20 | 10h | 00h | 1 | 0 | 0 | 0 | 0 | 0 |
mov bl, 7 | B3 07 | 10h | 07h | 1 | 0 | 0 | 0 | 0 | 0 |
sub bl, 9 | 80 EB 09 | 10h | FEh | 1 | 0 | 1 | 0 | 0 | 1 |
cmp al, 10h | 3C 10 | 10h | FEh | 0 | 1 | 0 | 0 | 1 | 0 |
cmp bl, 0 | 80 FB 00 | 10h | FEh | 0 | 0 | 1 | 0 | 0 | 0 |
add bl, 2 | 80 C3 02 | 10h | 00h | 1 | 1 | 0 | 0 | 1 | 1 |
Line 2. F0h + 20h = 110h. The low eight bits of this nine-bit result, 10h, are written to AL; the 1 that spills out falls into CF. In the signed reading −16 + 32 = 16 is correct and OF = 0. 10h = 0001 0000b has a single 1, PF = 0. Since the low nibbles are 0 + 0, AF = 0. The machine code is 04 20: 04 is the short accumulator form meaning "add an immediate byte to AL".
Line 4. 7 − 9 = −2, written in 8 bits in two's complement as FEh. Because a larger number was subtracted from a smaller one, a borrow was taken: CF = 1. The most significant bit of the result is 1, SF = 1. In the low nibbles too, 7 − 9 needs a borrow, AF = 1. In the signed reading 7 − 9 = −2 is correct and OF = 0. Because this instruction uses BL, not AL, the short form cannot be chosen; the general 80 /5 form takes three bytes.
Line 5. CMP AL, 10h performs the subtraction 10h − 10h = 0. The result is zero, ZF = 1. The result is not stored: AL is still 10h. This is the essence of an equality test: if two numbers are equal, their difference is zero and ZF = 1. If a JE (or JZ, the other name of the same instruction) follows immediately, the jump is taken. The CF = 1 and AF = 1 left from the previous line are also erased; CMP rewrites all the status flags.
Line 6. CMP BL, 0 is FEh − 0. The result is FEh: not zero (ZF = 0), sign bit 1 (SF = 1), no borrow (CF = 0). These three flags carry two different readings. Read as unsigned, FEh = 254 > 0; CF = 0 says so. Read as signed, FEh = −2 < 0; SF ≠ OF says so.
Line 7. FEh + 2 = 100h. 00h stays in BL; CF = 1 and ZF = 1. In the signed reading −2 + 2 = 0 is correct, OF = 0. This line shows the difference between CF and OF once more: CF = 1 does not mean the signed calculation is wrong.
6.3.2Comparing magnitudes with CMP
The real job of CMP is to find not whether two numbers are equal but which is larger. CMP A, B computes A − B. For unsigned numbers, if A < B the subtraction needs a borrow and CF = 1. For signed numbers the situation is subtler. If the difference did not overflow (OF = 0), the sign of the result is correct and if A < B then SF = 1. If the difference overflowed (OF = 1), the sign bit has flipped; this time A < B is shown by SF = 0. The two cases combine into a single rule: signed A < B ⇔ SF ≠ OF.
| Instructions | CF | SF | OF | Unsigned | Signed |
|---|---|---|---|---|---|
AL = 05h, BL = FEh; CMP AL, BL | 1 | 0 | 0 | 5 < 254 | 5 > −2 (SF = OF) |
AL = 7Fh, BL = 80h; CMP AL, BL | 1 | 1 | 1 | 127 < 128 | 127 > −128 (SF = OF) |
AL = 80h, BL = 01h; CMP AL, BL | 0 | 0 | 1 | 128 > 1 | −128 < 1 (SF ≠ OF) |
In the second row 7Fh − 80h = FFh: SF = 1. But signed 127 − (−128) = 255 does not fit in a byte, OF = 1. The sign bit is misleading here, and because SF = OF the correct decision is "greater". Conditional jumps offer these rules ready-made. For unsigned comparison JB/JA (below/above, which look at CF and ZF) are used, and for signed comparison JL/JG (less/greater, which look at SF, OF and ZF). Which jump is chosen after the same CMP determines how the numbers are interpreted.
6.3.332-bit addition with ADC
The 8086's ALU adds numbers of at most 16 bits. A number that does not fit in 16 bits, such as 131,071, is stored split into two words: DX holds the high word and AX the low word, and the pair is written DX:AX. To add two 32-bit numbers, the method of addition on paper is followed: first the digits on the right are added, and the carry is added to the digits on the left. Here a "digit" is a 16-bit word and the carry is carried in CF.
ADC (add with carry) performs destination ← destination + source + CF. SBB (subtract with borrow) performs destination ← destination − source − CF. Their operand rules and flag effect are the same as those of ADD and SUB.
; DX:AX = 0001FFFFh, CX:BX = 00020001h
mov ax, 0FFFFh
mov dx, 0001h
mov bx, 0001h
mov cx, 0002h
add ax, bx ; low words
adc dx, cx ; high + CF| Instruction | Machine code | DX | AX | CX | BX | CF | ZF |
|---|---|---|---|---|---|---|---|
mov ax, 0FFFFh | B8 FF FF | 0000h | FFFFh | 0000h | 0000h | 0 | 0 |
mov dx, 0001h | BA 01 00 | 0001h | FFFFh | 0000h | 0000h | 0 | 0 |
mov bx, 0001h · mov cx, 0002h | BB 01 00 · B9 02 00 | 0001h | FFFFh | 0002h | 0001h | 0 | 0 |
add ax, bx | 03 C3 | 0001h | 0000h | 0002h | 0001h | 1 | 1 |
adc dx, cx | 13 D1 | 0004h | 0000h | 0002h | 0001h | 0 | 0 |
The first number is DX:AX = 0001FFFFh = 131,071 and the second is CX:BX = 00020001h = 131,073. ADD AX, BX adds the low words: FFFFh + 0001h = 10000h. 0000h is written to AX and the 1 that comes out falls into CF. This CF is the carry to be carried to the high word. That ZF = 1 is misleading here: only the low word is zero, the 32-bit sum is not zero. ADC DX, CX uses this carry: 0001h + 0002h + 1 = 0004h. The result is DX:AX = 00040000h = 262,144, which agrees with 131,071 + 131,073.
The method is independent of the number of words. If a 48-bit number is held in three words, the first words are added with ADD and the next two words with ADC. The carry is carried in CF along the chain. No instruction that changes CF must come between ADD and ADC. MOV, INC, DEC and LOOP do not touch CF; so even when a counter is incremented inside a loop, the carry is preserved. In contrast, an ADD or CMP coming in between erases the carry.
6.3.432-bit subtraction with SBB
The same arrangement holds in subtraction. The lowest word is subtracted with SUB; if the low word is not enough, a borrow is taken from the next word up and this borrow waits in CF. SBB subtracts, from the upper word, this borrow together with the source.
; DX:AX = 00040000h, CX:BX = 00010001h
mov ax, 0000h
mov dx, 0004h
mov bx, 0001h
mov cx, 0001h
sub ax, bx ; low words
sbb dx, cx ; high - CF| Instruction | Machine code | DX | AX | CX:BX | CF | SF |
|---|---|---|---|---|---|---|
mov ax, 0000h · mov dx, 0004h | B8 00 00 · BA 04 00 | 0004h | 0000h | 0000:0000h | 0 | 0 |
mov bx, 0001h · mov cx, 0001h | BB 01 00 · B9 01 00 | 0004h | 0000h | 0001:0001h | 0 | 0 |
sub ax, bx | 2B C3 | 0004h | FFFFh | 0001:0001h | 1 | 1 |
sbb dx, cx | 1B D1 | 0002h | FFFFh | 0001:0001h | 0 | 0 |
The first number is 262,144 and the one subtracted is 65,537. SUB AX, BX performs 0000h − 0001h. The low word is not enough; a borrow is taken, AX = FFFFh and CF = 1. SBB DX, CX pays the borrow back: 0004h − 0001h − 1 = 0002h. The result is DX:AX = 0002FFFFh = 196,607, which agrees with 262,144 − 65,537.
How is 00012345h − 0000ABCDh done with SUB and SBB? What is CF after the SUB?
The first number is loaded as DX:AX = 0001:2345h and the second as CX:BX = 0000:ABCDh. SUB AX, BX: 2345h − ABCDh is negative; in 16 bits 12345h − ABCDh = 7778h remains and, because a borrow was taken, CF = 1. SBB DX, CX: 0001h − 0000h − 1 = 0000h. The result is 00007778h = 30,584 (74,565 − 43,981).
Using SUB (or ADD) for both words. Written this way, the borrow or carry from the low word is lost; the result comes out wrong by exactly 10000h. The rule: ADD/SUB on the lowest word, ADC/SBB on every following word.
6.4Logical operations
6.4.1Gates that work bit by bit
The logic instructions are the software counterparts of the gates known from digital design. Table 6.12 gives the truth tables of the four operations. AND gives 1 only if both inputs are 1. OR gives 1 if at least one input is 1. XOR gives 1 if the inputs differ. NOT has a single input and inverts it.
| A | B | A AND B | A OR B | A XOR B | NOT A |
|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | 1 |
| 0 | 1 | 0 | 1 | 1 | 1 |
| 1 | 0 | 0 | 1 | 1 | 0 |
| 1 | 1 | 1 | 1 | 0 | 0 |
The logic instructions of the 8086 apply these rules not to a number as a whole but to its bits one by one. The AND AL, BL instruction is really eight independent AND gates: bit 0 of AL is ANDed with bit 0 of BL, bit 1 with bit 1, and the result is written to the same bit of AL. No carry or borrow passes between neighboring bits. In the ALU this operation is done with the adder's carry chain disabled and the output of the right gate selected at each bit. That is why logic instructions are as fast as addition: 3 clock cycles between registers.
A consequence of processing bit by bit is that carry and overflow are meaningless. The 8086 states this explicitly: after AND, OR, XOR and TEST, CF = 0 and OF = 0. ZF, SF and PF are set according to the result, AF is undefined. NOT is an exception: it changes no flag.
6.4.2Masking
The most common use of logic instructions is to change some bits of a number and preserve the others. For this a mask is given as the second operand. Each bit of the mask chooses what happens to the corresponding bit. This method is called masking.
- Clearing bits with AND. x AND 0 = 0, x AND 1 = x. Bits that are 0 in the mask are cleared, those that are 1 are preserved.
- Setting bits with OR. x OR 1 = 1, x OR 0 = x. Bits that are 1 in the mask become 1 for certain, those that are 0 are preserved.
- Inverting bits with XOR. x XOR 1 = NOT x, x XOR 0 = x. Bits that are 1 in the mask are inverted, those that are 0 are preserved.
- Testing bits with TEST. TEST does an AND but does not write the result. If the bit in the mask (or one of the bits) is 1 and the number also has a 1 there, the result is nonzero: ZF = 0. The number does not change.
In ASCII encoding, uppercase and lowercase letters differ only in bit 5: 'A' = 41h = 0100 0001b, 'a' = 61h = 0110 0001b. So the conversion of a letter is done with a single logic instruction. Figure 6.4 shows the four operations with the same letters.
The meaning of the mask values is plain when they are written in binary. DFh = 1101 1111b is a mask with only bit 5 equal to 0; with AND it clears bit 5. 20h = 0010 0000b is a mask with only bit 5 equal to 1; with OR it sets bit 5 and with XOR it inverts it. In the last figure BL = '7' = 37h = 0011 0111b is TESTed with the mask 01h. The result is 01h ≠ 0, so ZF = 0: bit 0 is one, that is, the number is odd.
6.4.3Frequently used patterns
Some uses of logic instructions are so common that they have become almost fixed patterns in assembly programs. Table 6.13 collects the most frequently met.
| Code | Effect | Why? |
|---|---|---|
XOR AX, AX | AX = 0, ZF = 1, CF = 0 | 2 bytes (33 C0); MOV AX, 0 is 3 bytes (B8 00 00) and does not touch the flags |
AND AL, 0Fh | '7' (37h) → 7 | converts an ASCII digit to a number; the high nibble is cleared |
OR AL, 30h | 7 → '7' (37h) | converts a number from 0 to 9 to an ASCII digit |
AND AL, 0DFh | 'a' → 'A' | clears bit 5: uppercase |
OR AL, 20h | 'A' → 'a' | sets bit 5: lowercase |
TEST AL, 1 | odd if ZF = 0 | bit 0 is tested without changing AL |
TEST AL, 80h | negative if ZF = 0 | the sign bit is tested |
OR AX, AX | AX unchanged | ZF and SF are set: is AX zero, is it negative? |
ASCII digits run from '0' = 30h to '9' = 39h. The high nibble is 3 for every digit, and the low nibble is the value of the digit. Because AND AL, 0Fh clears the high nibble, it converts a digit read from the keyboard to a number. OR AL, 30h does the reverse and prepares a character to be written on the screen. The same job can be done with SUB AL, 30h and ADD AL, 30h; the difference with the logic instructions is that they still give the right result if the input has already been converted.
OR AX, AX looks meaningless at first sight: ORing a number with itself does not change it. The purpose of the instruction is the flags. If AX is zero, ZF = 1; if its most significant bit is 1, SF = 1. The same job is done with TEST AX, AX and CMP AX, 0. OR and TEST take two bytes; CMP takes three because it also carries the constant.
6.4.4Code trace: AND, OR, XOR, TEST
mov al, 'a' ; 61h
and al, 0DFh ; uppercase
or al, 20h ; lowercase
xor al, 20h ; flip case
mov bl, '7' ; 37h
and bl, 0Fh ; number 7
test bl, 1 ; odd?
xor bl, bl ; BL = 0| Instruction | Machine code | AL | BL | ZF | SF | PF | CF | OF |
|---|---|---|---|---|---|---|---|---|
mov al, 'a' | B0 61 | 61h | 00h | 0 | 0 | 0 | 0 | 0 |
and al, 0DFh | 24 DF | 41h 'A' | 00h | 0 | 0 | 1 | 0 | 0 |
or al, 20h | 0C 20 | 61h 'a' | 00h | 0 | 0 | 0 | 0 | 0 |
xor al, 20h | 34 20 | 41h 'A' | 00h | 0 | 0 | 1 | 0 | 0 |
mov bl, '7' | B3 37 | 41h | 37h | 0 | 0 | 1 | 0 | 0 |
and bl, 0Fh | 80 E3 0F | 41h | 07h | 0 | 0 | 0 | 0 | 0 |
test bl, 1 | F6 C3 01 | 41h | 07h | 0 | 0 | 0 | 0 | 0 |
xor bl, bl | 32 DB | 41h | 00h | 1 | 0 | 1 | 0 | 0 |
61h AND DFh = 41h = 'A'. 41h = 0100 0001b has two 1s, PF = 1. 41h OR 20h = 61h = 'a'; 0110 0001b has three 1s, PF = 0. 61h XOR 20h gives 41h again: bit 5 has been inverted. Applying XOR twice brings the number back to its old state; this property is used in simple encryption and bit-toggling jobs.
ASCII '7' = 37h is loaded into BL and AND BL, 0Fh turns it into the numeric 7. TEST BL, 1 computes 07h AND 01h = 01h; the result is nonzero, ZF = 0 and the number is odd. BL stays 07h unchanged. On the last line BL is XORed with itself. Because no bit differs from itself, the result is 00h; ZF = 1. Zero 1 bits is an even count, PF = 1.
The machine code column of the table shows the short forms of instructions that work with AL. AND AL, imm8 = 24, OR AL, imm8 = 0C, XOR AL, imm8 = 34 are two-byte instructions. The same operations with BL fall to the general 80 or F6 form and take three bytes. This is a small but constant advantage that AL and AX have as the accumulator.
Using AND to test a bit and spoiling the number. AND AL, 80h looks at the sign bit but clears the other seven bits of AL. If the number will be used again, TEST should be written. The same relation exists between CMP and SUB.
6.5Multiplication and division
6.5.1MUL and IMUL
The product of two 8-bit numbers can be up to 16 bits, and that of two 16-bit numbers up to 32 bits: 255 × 255 = 65,025 does not fit in a byte, only in a word. The 8086 therefore always writes the result of a multiplication to a place twice the width of the operand. The other operand of the multiplication and the place of the result are fixed; only one operand is written in the instruction. Figure 6.5 shows the two sizes.
MUL does unsigned and IMUL signed multiplication. If the operand is a byte, AX ← AL × operand; if the operand is a word, DX:AX ← AX × operand. The operand can be a register or a memory operand (MUL BL, IMUL WORD PTR [SI]). The 8086 has no immediate operand: MUL 5 is invalid.
Whether the product is unsigned or signed changes the bits of the result; unlike addition, a single operation does not serve both readings. For AL = C8h and BL = 03h, MUL BL gives 200 × 3 = 600 = 0258h. With the same bits IMUL BL reads C8h as −56 and gives −56 × 3 = −168 = FF58h. The low bytes (58h) are the same, the high bytes differ. That is why the 8086 has two separate multiplication instructions.
After multiplication only CF and OF are meaningful, and the two are always equal. If the upper half of the result (AH or DX) is really needed, CF = OF = 1. For MUL "needed" means the upper half is nonzero. For IMUL it means the upper half differs from the sign extension of the lower half: if the result fits the lower half as a signed number, the upper half is only copies of the sign bit and carries no information. SF, ZF, AF and PF are undefined after multiplication.
| AL, BL | Instruction | Calculation | AX | CF = OF | Why |
|---|---|---|---|---|---|
| C8h, 03h | MUL BL | 200 × 3 = 600 | 0258h | 1 | AH = 02h ≠ 0 |
| C8h, 03h | IMUL BL | −56 × 3 = −168 | FF58h | 1 | −168 does not fit a signed byte |
| FEh, 05h | IMUL BL | −2 × 5 = −10 | FFF6h | 0 | AH = FFh, the sign extension of AL |
| FEh, 05h | MUL BL | 254 × 5 = 1270 | 04F6h | 1 | AH = 04h ≠ 0 |
| 06h, 09h | MUL BL | 6 × 9 = 54 | 0036h | 0 | AH = 0 |
Multiplication is one of the slowest instructions of the 8086. There is no hardware multiplier in the ALU; the EU applies the shift-and-add method bit by bit in microcode. According to Intel's manual, MUL with a register operand takes 70–77 clock cycles for a byte and 118–133 for a word; IMUL takes 80–98 for a byte and 128–154 for a word. If there is a memory operand, a few more cycles are added with the EA time. The time is given as a range because the microcode loop passes through different paths depending on the bits of the multiplier. Since an addition takes only 3 cycles, turning multiplication by a constant into shifts and additions is often worthwhile.
6.5.2DIV and IDIV
Division, as the inverse of multiplication, needs a dividend twice the width of the operand. If the divisor is a byte, the dividend is AX; if the divisor is a word, the dividend is DX:AX. The result is in two parts: the quotient and the remainder. Figure 6.6 shows word division.
| Instruction | If the operand is a byte | If the operand is a word |
|---|---|---|
DIV (unsigned) | AL ← AX / operand, AH ← remainder | AX ← DX:AX / operand, DX ← remainder |
IDIV (signed) | AL ← AX / operand, AH ← remainder | AX ← DX:AX / operand, DX ← remainder |
After division all the status flags are undefined; no information about the result of the division can be got from the flags. Division is slower than multiplication: DIV with a register takes 80–90 cycles for a byte and 144–162 for a word; IDIV takes 101–112 for a byte and 165–184 for a word.
IDIV truncates the quotient toward zero and leaves the remainder with the same sign as the dividend. For −23 / 5 the quotient is −4.6; truncated toward zero it becomes −4. The remainder is found from −23 = (−4) × 5 + remainder as −3. With this rule the equality dividend = quotient × divisor + remainder always holds and the absolute value of the remainder is smaller than the divisor.
A divide error occurs when the divisor is 0 or when the quotient does not fit in its destination (AL or AX). The processor does not complete the division; it raises interrupt number 0 (INT 0). The first entry of the interrupt vector table (0000:0000) points to the service routine of this interrupt. DOS prints the message "Divide overflow" in this routine and terminates the program.
Whether the quotient will fit is easy to test before the division. In byte division the quotient must not exceed 255; this holds only if AH < divisor. In word division the same rule takes the form DX < divisor. For AX = 1000h (4096) and BL = 2, AH = 10h ≥ 2: the quotient 2048 does not fit in AL and a divide error occurs. For DX:AX = FFFFFFFFh and BX = 1 too, although the divisor is not zero, DX = FFFFh ≥ 1 and the quotient does not fit. In IDIV the limit is slightly narrower: on the 8086 the byte quotient must be in the range −127…127 and the word quotient in −32,767…32,767; −128 and −32,768 also cause a divide error.
The return address that the 8086 pushes on the stack at a divide error carries one more detail. The IP pushed when the INT 0 service is called points to the instruction after the division instruction. On the 80286 and later processors it points to the division instruction itself, so that the instruction can be retried after the error is removed. This difference concerns only programs that write their own INT 0 routine.
6.5.3Multiplication and division step by step
Table 6.17 collects the step-by-step multiplication and division examples of the slides in one table. Each row is an independent experiment; the registers start with the values given at the start of the row.
| Start | Instruction | Result | Explanation |
|---|---|---|---|
| AL = C8h, BL = 03h | MUL BL | AX = 0258h, CF = OF = 1 | 200 × 3 = 600; did not fit in AL |
| AL = C8h, BL = 03h | IMUL BL | AX = FF58h, CF = OF = 1 | −56 × 3 = −168; does not fit a signed byte |
| AL = FEh, BL = 05h | IMUL BL | AX = FFF6h, CF = OF = 0 | −2 × 5 = −10; AH is only the sign extension |
| AX = 0017h, BL = 05h | DIV BL | AL = 04h, AH = 03h (AX = 0304h) | 23 = 4 × 5 + 3 |
| AX = FFE9h, BL = 05h | IDIV BL | AL = FCh, AH = FDh (AX = FDFCh) | −23 = (−4) × 5 + (−3) |
| AX = 1000h, BL = 02h | DIV BL | INT 0 | the quotient 2048 does not fit in AL |
| DX:AX = FFFFFFFFh, BX = 0001h | DIV BX | INT 0 | the quotient FFFFFFFFh does not fit in AX |
In the fourth row AX = 0017h = 23 and BL = 5. The quotient 4 is written to AL and the remainder 3 to AH, and the new AX is 0304h. This value should not be read as a number; the two halves of AX now carry two separate results. In the fifth row the negative of the same number is divided. −23 = FFE9h. The quotient is −4 = FCh and the remainder −3 = FDh; check: −4 × 5 + (−3) = −23.
6.5.4Preparing for division: CBW and CWD
Because the dividend is always twice the width of the divisor, the dividend must be extended before the division. The number to be divided is often only in AL or in AX; the programmer decides what the upper half (AH or DX) will be.
- Before an unsigned division the upper half is zeroed:
MOV AH, 0orXOR DX, DX. The value of the number does not change; zeros are only added in front of it. - Before a signed division the sign is extended: the sign bit is copied into all the bits of the upper half. The 8086 has two instructions for this.
Sign extension is moving a signed number to a wider place while preserving its value: the most significant bit is copied into all the newly added bits. CBW (convert byte to word) extends AL into AX: if bit 7 of AL is 0, AH = 00h; if 1, AH = FFh. CWD (convert word to doubleword) extends AX into DX:AX: if bit 15 of AX is 0, DX = 0000h; if 1, DX = FFFFh. Neither instruction takes an operand and neither changes any flag.
F9h as a signed byte is −7. The same −7 written as a word is FFF9h: 65,536 − 7 = 65,529 = FFF9h. CBW does this conversion in a single instruction and takes 2 clock cycles. CWD takes 5. Both use implicit operands and are one-byte instructions (98 and 99).
; unsigned: 1000 / 7
mov ax, 1000
xor dx, dx ; DX:AX = 1000
mov bx, 7
div bx ; AX = 142, DX = 6
; signed: -1000 / 7
mov ax, -1000
cwd ; DX = FFFFh
idiv bx ; AX = -142, DX = -6In the first part 1000 = 03E8h is loaded into AX and DX is zeroed; the dividend becomes DX:AX = 000003E8h. 1000 / 7 = 142, remainder 6: AX = 008Eh, DX = 0006h. In the second part −1000 = FC18h is loaded. Because bit 15 is one, CWD puts FFFFh into DX and DX:AX = FFFFFC18h, which is −1000 in 32 bits. IDIV gives the quotient −142 = FF72h and the remainder −6 = FFFAh.
Forgetting DX before a word division. A number left in DX from an earlier operation enlarges the dividend. If XOR DX, DX is written instead of CWD for signed −1000, the dividend becomes 0000FC18h = 64,536. IDIV then gives a meaningless result such as 64,536 / 7 = 9219 (2403h). If a large value is left in DX, the quotient does not fit and the program stops with a divide error.
6.5.5Code trace: DIV, CWD and IDIV
The following program does the same division job three times: first unsigned, then signed, and last forgetting to clear DX.
MOV AX, 2000
XOR DX, DX ; DX:AX = 2000
MOV BX, 9
DIV BX ; unsigned div
MOV AX, -2000
CWD ; sign-extend
IDIV BX ; signed div
MOV AX, 2000 ; DX not cleared!
DIV BX
RET| Instruction | Machine code | DX | AX | BX | DX:AX (decimal) |
|---|---|---|---|---|---|
MOV AX, 2000 | B8 D0 07 | 0000h | 07D0h | 0000h | 2000 |
XOR DX, DX | 33 D2 | 0000h | 07D0h | 0000h | 2000 |
MOV BX, 9 | BB 09 00 | 0000h | 07D0h | 0009h | 2000 |
DIV BX | F7 F3 | 0002h | 00DEh | 0009h | quotient 222, remainder 2 |
MOV AX, -2000 | B8 30 F8 | 0002h | F830h | 0009h | 0002F830h = 194,608 (wrong dividend) |
CWD | 99 | FFFFh | F830h | 0009h | FFFFF830h = −2000 |
IDIV BX | F7 FB | FFFEh | FF22h | 0009h | quotient −222, remainder −2 |
MOV AX, 2000 | B8 D0 07 | FFFEh | 07D0h | 0009h | FFFE07D0h ≈ 4.29 billion |
DIV BX | F7 F3 | divide error: DX = FFFEh ≥ 9, the quotient does not fit in AX → INT 0 | |||
In the first division 2000 / 9 = 222, remainder 2: AX = 00DEh, DX = 0002h. The fifth row shows why CWD is needed. −2000 = F830h has been loaded into AX but DX still holds the remainder of the previous division (2). IDIV, which reads DX:AX as a 32-bit number, would divide 194,608 in this state. Because the sign bit of AX is 1, CWD writes FFFFh into DX and makes the dividend correctly −2000. For −2000 / 9, IDIV gives the quotient −222 = FF22h and the remainder −2 = FFFEh. The remainder, like the dividend, is negative.
The last two rows act out the classic mistake. 2000 has been loaded into AX, but DX still holds the remainder of IDIV (FFFEh). The unsigned dividend FFFE07D0h is about 4.29 billion. Dividing this by 9 gives a quotient that does not fit in 16 bits; the rule says so in advance: DX = FFFEh ≥ 9. The processor raises INT 0 and the program stops. The fix is to write XOR DX, DX before the division.
6.5.6Signed overflow: JO and CBW
The sum of two signed bytes may not fit in a byte. In that case the correct result is found by first extending the two numbers to words and adding them in 16 bits. The program below first tries the byte addition; if overflow occurs, it switches to the word addition. There are two jump instructions in the program. JO label (jump if overflow) jumps to the given label if OF = 1 and otherwise goes on to the next instruction. JMP label jumps unconditionally. Its opposite, JNO, jumps if OF = 0.
mov al, -92 ; A4h
mov bl, -92
add al, bl ; 8-bit add
jo widen ; if OF = 1
jmp done
widen:
mov al, -92 ; first number
cbw ; AL -> AX
mov dx, ax
mov al, bl ; second number
cbw
add ax, dx ; 16-bit add
done:
ret| Instruction | AX | DX | CF | OF | SF | Explanation |
|---|---|---|---|---|---|---|
mov al, -92 · mov bl, -92 | 00A4h | 0000h | 0 | 0 | 0 | −92 = 256 − 92 = 164 = A4h |
add al, bl | 0048h | 0000h | 1 | 1 | 0 | A4h + A4h = 148h; AL = 48h = +72 |
jo widen | 0048h | 0000h | 1 | 1 | 0 | OF = 1: the jump is taken |
mov al, -92 · cbw | FFA4h | 0000h | 1 | 1 | 0 | the MSB of AL is 1 → AH = FFh |
mov dx, ax · mov al, bl · cbw | FFA4h | FFA4h | 1 | 1 | 0 | both numbers are −92 as words |
add ax, dx | FF48h | FFA4h | 1 | 0 | 1 | FFA4h + FFA4h = 1FF48h; AX = −184 |
In the byte addition the sum of two negative numbers has come out positive: AL = 48h = +72. The correct result is −184 and is not in the range −128…127. Because OF = 1, JO jumps to the widen label. CF = 1 as well, but CF has no meaning in the signed reading. In the extension part the first number is loaded into AL again and extended to FFA4h with CBW. It is saved in DX. The second number is taken from BL and extended too. The 16-bit sum is FFA4h + FFA4h = 1FF48h; the 1 that comes out falls into CF, and FF48h = −184 stays in AX. The result fits the word, OF = 0.
6.5.7Summing a signed byte array with CBW
The same idea can be applied to all the elements of an array. The program below accumulates four signed bytes in a 16-bit sum. The program uses a loop, and the loop is built with the LOOP instruction.
The LOOP label instruction does two things: it decrements CX by 1 and then, if CX is nonzero, jumps to the label; if CX has become zero it goes on to the next instruction. Before the loop, CX is loaded with the number of iterations. A loop body that starts with CX = 4 runs four times. LOOP changes no flag; the decrement of CX is not reflected in the flags either.
org 100h
jmp start
arr db 100, -30, 90, -7
total dw 0
start:
lea si, arr
mov cx, 4
xor bx, bx ; BX = 16-bit sum
again:
mov al, [si]
cbw ; AL -> AX (signed)
add bx, ax
inc si
loop again
mov total, bx ; 153 = 0099h
retThe JMP start at the beginning of the program jumps over the data definitions. In a .COM program code and data are in the same segment and the processor starts at 0100h; without the jump the bytes of the array would be taken for instructions. LEA SI, arr loads the offset of the array (0102h) into SI. emu8086 turns this line into the same three-byte code as MOV SI, 0102h (BE 02 01). BX holds the sum and is zeroed.
| Iteration | AL | AX after CBW | BX (sum) | CX (at the start of the iteration) | Explanation |
|---|---|---|---|---|---|
| 1 | 64h | 0064h | 0064h = 100 | 4 | +100, MSB = 0 → AH = 00h |
| 2 | E2h | FFE2h | 0046h = 70 | 3 | −30, MSB = 1 → AH = FFh |
| 3 | 5Ah | 005Ah | 00A0h = 160 | 2 | +90 |
| 4 | F9h | FFF9h | 0099h = 153 | 1 | −7; CX = 0 after LOOP |
In the second iteration FFE2h is added to BX = 0064h: 0064h + FFE2h = 1 0046h. The carry that comes out is discarded and BX = 0046h = 70 remains; 100 + (−30) = 70 is correct. This is a well-known property of two's complement: adding a negative number gives the same result as subtracting when the carry is discarded. In the third iteration the sum becomes 160. If the addition had been done in bytes, 70 + 90 = 160 > 127 would have given AL = A0h (−96) and OF = 1. In a word 160 fits easily. After the loop the total = 0099h = 153 is written to memory.
Using MOV AH, 0 when extending signed bytes. This extends the number as unsigned: −30 = E2h is added as 00E2h = 226; −7 is counted as 249 too, and the total comes out 665 instead of 153. MOV AH, 0 is used for unsigned data and CBW for signed data.
6.5.8A 32-bit total with CWD and ADC
When the elements are words the total may not fit in 16 bits either. The solution is to extend each element to 32 bits with CWD and accumulate in a 32-bit total with an ADD-ADC pair.
org 100h
jmp start
arr dw 30000, 25000, -4000
total dw 0, 0 ; 32-bit total
start:
lea si, arr
mov cx, 3
again:
mov ax, [si]
cwd ; AX -> DX:AX
add [total], ax ; low word
adc [total+2], dx ; high + CF
add si, 2
loop again
retThe total is two words: the low word is at total and the high word at total+2. In a word array every element takes two bytes, so SI increases by 2 in each iteration.
| Iteration | AX | CWD: DX | Total after ADD, CF | total+2 after ADC | 32-bit total |
|---|---|---|---|---|---|
| 1 | 7530h (30.000) | 0000h | 7530h, CF = 0 | 0000h | 00007530h = 30.000 |
| 2 | 61A8h (25.000) | 0000h | D6D8h, CF = 0 | 0000h | 0000D6D8h = 55.000 |
| 3 | F060h (−4000) | FFFFh | C738h, CF = 1 | 0000h | 0000C738h = 51.000 |
In the second iteration 7530h + 61A8h = D6D8h. In the 16-bit signed reading this number is negative and OF = 1; but because the total is kept in 32 bits there is no problem: the high word is 0000h and 55,000 is correct. In the third iteration the sign bit of −4000 = F060h is 1; CWD puts FFFFh into DX and DX:AX = FFFFF060h, which is −4000 in 32 bits. In the low word D6D8h + F060h = 1C738h; the total becomes C738h and CF = 1. In the high word 0000h + FFFFh + 1 = 10000h; total+2 = 0000h remains. The result is 0000C738h = 51,000 = 30,000 + 25,000 − 4000.
The add si, 2 in the program changes CF, but this is not a problem, because the carry of the next iteration starts afresh with ADD. The carry must be preserved only between an ADD and the ADC right after it. These two instructions use a memory operand: each reads the word, adds, and writes it back. On the 8086 each takes 16 + EA clock cycles and needs two bus cycles (a read and a write).
6.5.932 × 32-bit multiplication
The 8086 multiplies at most 16 × 16 bits. The product of two 32-bit numbers is done with the method of multiplication on paper, using 16-bit "digits". If A = A1:A0 and B = B1:B0 are split into halves, then
A × B = A1·B1·232 + (A1·B0 + A0·B1)·216 + A0·B0
holds. Each of the four partial products is computed with one MUL and its 32-bit result lands in DX:AX. The partial products are added to the four words of the result (z3:z2:z1:z0, 64 bits in total) according to their positions. A product multiplied by 216 is shifted left by one word and is added to z2:z1; the one multiplied by 232 is shifted left by two words and is added to z3:z2.
In the example A = 9ABCDEF0h and B = EDCBFEDCh. The partial products are A0 × B0 = DDF1B640h, A1 × B0 = 9A0B8190h, A0 × B1 = CF14F850h and A1 × B1 = 8FBABF14h. In the z0 column there is only B640h. The sum of the z1 column is DDF1h + 8190h + F850h = 257D1h: 57D1h is written and a carry of 2 passes to z2. The z2 column is 9A0Bh + CF14h + BF14h + 2 = 22835h: 2835h is written and a carry of 2 passes to z3. z3 = 8FBAh + 2 = 8FBCh. The result is 8FBC 2835 57D1 B640h. Decimal check: 2,596,069,104 × 3,989,569,244 = 10,357,197,452,617,037,376.
A column carry can be 2, but an ADD gives at most a carry of 1. The code therefore does the additions one at a time and carries the carry of each ADD to the next word up at once with an ADC.
org 100h
mov ax, [x] ; A0
mul [y] ; A0*B0
mov [z], ax
mov [z+2], dx
mov ax, [x+2] ; A1
mul [y] ; A1*B0
add [z+2], ax
adc [z+4], dx
mov ax, [x] ; A0
mul [y+2] ; A0*B1
add [z+2], ax
adc [z+4], dx
adc [z+6], 0
mov ax, [x+2] ; A1
mul [y+2] ; A1*B1
add [z+4], ax
adc [z+6], dx
ret
x dw 0DEF0h, 9ABCh ; A = 9ABCDEF0h
y dw 0FEDCh, 0EDCBh ; B = EDCBFEDCh
z dw 4 dup(0) ; 64-bit result| Instruction(s) | DX:AX | CF | z3 | z2 | z1 | z0 |
|---|---|---|---|---|---|---|
mov ax,[x] · mul [y] | DDF1:B640h | 1 | 0000h | 0000h | 0000h | 0000h |
mov [z],ax · mov [z+2],dx | DDF1:B640h | 1 | 0000h | 0000h | DDF1h | B640h |
mov ax,[x+2] · mul [y] | 9A0B:8190h | 1 | 0000h | 0000h | DDF1h | B640h |
add [z+2],ax | 9A0B:8190h | 1 | 0000h | 0000h | 5F81h | B640h |
adc [z+4],dx | 9A0B:8190h | 0 | 0000h | 9A0Ch | 5F81h | B640h |
mov ax,[x] · mul [y+2] | CF14:F850h | 1 | 0000h | 9A0Ch | 5F81h | B640h |
add [z+2],ax | CF14:F850h | 1 | 0000h | 9A0Ch | 57D1h | B640h |
adc [z+4],dx | CF14:F850h | 1 | 0000h | 6921h | 57D1h | B640h |
adc [z+6],0 | CF14:F850h | 0 | 0001h | 6921h | 57D1h | B640h |
mov ax,[x+2] · mul [y+2] | 8FBA:BF14h | 1 | 0001h | 6921h | 57D1h | B640h |
add [z+4],ax | 8FBA:BF14h | 1 | 0001h | 2835h | 57D1h | B640h |
adc [z+6],dx | 8FBA:BF14h | 0 | 8FBCh | 2835h | 57D1h | B640h |
After the first MUL, DX ≠ 0, so CF = 1; this CF only says "the result did not fit in 16 bits" and has nothing to do with the following additions. In the second partial product z1 + AX = DDF1h + 8190h = 1 5F81h; z1 becomes 5F81h and CF = 1. ADC makes z2 = 0 + 9A0Bh + 1 = 9A0Ch. Since z2 was zero before, no new carry arises here.
The third partial product is more interesting. z1 = 5F81h + F850h = 1 57D1h; the carry goes to z2. z2 = 9A0Ch + CF14h + 1 = 1 6921h; this time the carry must spill into z3. The adc [z+6], 0 instruction does this job: it adds no number to z3, only the carry, and z3 = 0001h. If this line is forgotten, the result comes out short by exactly 248. The fourth partial product is added to z3:z2: z2 = 6921h + BF14h = 1 2835h, z3 = 0001h + 8FBAh + 1 = 8FBCh. In memory z holds, in order, the bytes 40 B6 D1 57 35 28 BC 8F; in little-endian order this is 8FBC283557D1B640h.
Each of the four MULs takes 124–139 cycles plus EA; the whole program takes over 600 cycles on the 8086. On the 80386 the same job is done with a single 32-bit MUL. This is the price of multiword arithmetic on a 16-bit processor.
6.6Single-operand instructions
6.6.1INC, DEC, NOT and NEG
The four instructions in the third group take a single operand. The operand can be a register (AX, BX, …, SP or the 8-bit halves) or a memory operand; it cannot be a constant. With a memory operand the size must be specified: INC BYTE PTR [BX]. The instruction reads the operand, changes it, and writes it back to the same place.
- INC adds 1 to the operand and DEC subtracts 1. They set ZF, SF, OF, PF and AF according to the result, but do not touch CF.
- NOT inverts every bit. The result is the operand's ones' complement. It changes no flag.
- NEG changes the sign of the operand: it computes 0 − operand. The result is the two's complement: the bits are inverted and 1 is added. It sets all six status flags; CF is 1 if the operand is nonzero and 0 if it is zero.
| Instruction | CF | ZF | SF | OF | PF | AF |
|---|---|---|---|---|---|---|
INC, DEC | — | ✓ | ✓ | ✓ | ✓ | ✓ |
NOT | — | — | — | — | — | — |
NEG | ✓ (1 if operand ≠ 0) | ✓ | ✓ | ✓ | ✓ | ✓ |
That INC and DEC preserve CF is a design decision. In multibyte or multiword addition, the loop does an ADC on each iteration and carries the carry to the next iteration. The same loop advances the pointer with INC and decrements the counter with DEC. If these two instructions erased CF, the carry would be lost. The 8086 designers therefore left INC and DEC independent of CF.
INC and DEC are also very short instructions. INC SI, which increments a 16-bit register, is a single byte (46) and takes 2 clock cycles; ADD SI, 1 is three bytes and 4 cycles. On an 8-bit register INC is two bytes (such as FE C0) and 3 cycles, and in memory 15 + EA cycles. NEG and NOT take 3 cycles on a register and 16 + EA in memory.
6.6.2NEG: two's complement step by step
Two's complement is the standard way of representing negative numbers in binary. The negative of a number is found by inverting its bits and adding 1. NEG does these two steps in a single instruction. Figure 6.9 shows the negative of 5 and of −128 step by step.
| x | NOT x | NEG x | CF | OF | Explanation |
|---|---|---|---|---|---|
| 05h (5) | FAh (−6) | FBh (−5) | 1 | 0 | the negative of a positive |
| FEh (−2) | 01h | 02h (2) | 1 | 0 | the negative of a negative is positive |
| 80h (−128) | 7Fh | 80h | 1 | 1 | +128 does not fit in a byte |
| 00h | FFh | 00h | 0 | 0 | ZF = 1; the only case with CF = 0 |
The value of the ones' complement is always 1 less than the two's complement: NOT 5 = −6, NEG 5 = −5. The case of −128 is special. The signed byte range is −128…127 and +128 is not in this range. NEG 80h gives 80h again and reports the overflow with OF = 1. The CF rule of NEG also comes from the subtraction 0 − x: if x is not zero, subtracting a positive number from 0 needs a borrow and CF = 1; if x = 0 no borrow is needed.
6.6.3Code trace: INC, DEC, NOT, NEG
mov al, 0FFh
inc al ; FFh + 1
dec al ; 00h - 1
mov bl, 7Fh ; +127
inc bl ; +128 ?
not bl
neg bl| Instruction | Machine code | AL | BL | CF | ZF | SF | OF | PF | AF |
|---|---|---|---|---|---|---|---|---|---|
mov al, 0FFh | B0 FF | FFh | 00h | 0 | 0 | 0 | 0 | 0 | 0 |
inc al | FE C0 | 00h | 00h | 0 | 1 | 0 | 0 | 1 | 1 |
dec al | FE C8 | FFh | 00h | 0 | 0 | 1 | 0 | 1 | 1 |
mov bl, 7Fh | B3 7F | FFh | 7Fh | 0 | 0 | 1 | 0 | 1 | 1 |
inc bl | FE C3 | FFh | 80h | 0 | 0 | 1 | 1 | 0 | 1 |
not bl | F6 D3 | FFh | 7Fh | 0 | 0 | 1 | 1 | 0 | 1 |
neg bl | F6 DB | FFh | 81h | 1 | 0 | 1 | 0 | 1 | 1 |
INC AL makes FFh into 00h and ZF = 1. With ADD AL, 1, CF = 1 would result; INC does not change CF and CF stays 0. DEC AL computes 00h − 1 = FFh. A borrow was needed, but CF again does not change; only SF = 1. These two lines show that the only way to tell from the flags whether INC and DEC wrapped around is ZF and SF.
BL is loaded with the largest positive byte, 7Fh = +127. With INC BL BL becomes 80h: in the unsigned reading 128 is correct, in the signed reading it is −128. A signed overflow has occurred, OF = 1. NOT BL turns 80h into 7Fh but does not touch the flags: SF still looks 1, although the sign bit of BL is now 0. This shows that looking at the flags after NOT can be misleading. NEG BL takes the negative of +127: −127 = 81h. Because the operand is not zero, CF = 1; the result is in range, OF = 0.
6.7Shifts and rotates
6.7.1Shifts: SHL/SAL, SHR, SAR
Shift instructions move all the bits of a number in one direction. The bit that leaves at one end falls into CF, and a new bit enters at the other end. The instruction decides what the entering bit will be. It is the software counterpart of the shift register of digital design; the only difference is that the 8086 does the shift with an instruction rather than with a clock pulse. Figure 6.10 shows the bit flow of the three shifts.
SHL (shift logical left), and its other name SAL, shifts the bits left; 0 enters from the right and the most significant bit goes out to CF. Each shift multiplies an unsigned number by 2. SHR (shift logical right) is the logical shift: 0 enters from the left and the least significant bit goes out to CF; it divides an unsigned number by 2. SAR (shift arithmetic right) is the arithmetic shift: the most significant bit stays in place and is also copied to the right; it divides a signed number by 2.
With the example 96h = 1001 0110b the three shifts work as follows. SHL AL, 1: the bits move left, b7 (1) goes out to CF, 0 enters from the right: 0010 1100b = 2Ch, CF = 1. The unsigned 150 × 2 = 300 did not fit in a byte; CF shows this. SHR AL, 1: b0 (0) goes out to CF, 0 enters from the left: 0100 1011b = 4Bh = 75 = 150 / 2. SAR AL, 1: the sign bit 1 is copied: 1100 1011b = CBh = −53. In the signed reading 96h = −106 and −106 / 2 = −53 is correct.
The division by SAR rounds differently from that of IDIV. SAR always rounds toward minus infinity; IDIV truncates toward zero. For positive numbers the two give the same result; for negative odd numbers they part. For −7 = F9h, SAR AL, 1 gives FCh = −4 (−3.5 has been rounded down). For −7 / 2, IDIV gives −3. This difference must be kept in mind when turning division into shifting.
6.7.2Rotates: ROL, ROR, RCL, RCR
Rotate instructions resemble shifts, but the bit that leaves at one end is not lost; it comes back in at the other end. The bits turn around a ring. Figure 6.11 shows the bit flow of the four rotates.
- ROL (rotate left): b7 goes both to b0 and to CF.
- ROR (rotate right): b0 goes both to b7 and to CF.
- RCL (rotate left through CF): b7 goes to CF, the old CF goes to b0.
- RCR (rotate right through CF): b0 goes to CF, the old CF goes to b7.
| Instruction | With CF = 0 | With CF = 1 | Result CF | OF |
|---|---|---|---|---|
SHL AL, 1 | 2Ch (0010 1100) | 2Ch | 1 | 1 |
SHR AL, 1 | 4Bh (0100 1011) | 4Bh | 0 | 1 |
SAR AL, 1 | CBh (1100 1011) | CBh | 0 | 0 |
ROL AL, 1 | 2Dh (0010 1101) | 2Dh | 1 | 1 |
ROR AL, 1 | 4Bh (0100 1011) | 4Bh | 0 | 1 |
RCL AL, 1 | 2Ch (0010 1100) | 2Dh (0010 1101) | 1 | 1 |
RCR AL, 1 | 4Bh (0100 1011) | CBh (1100 1011) | 0 | 1 / 0 |
In a rotate no bit is lost. 1234h rotated CL = 8 times with ROL AX, CL becomes 3412h: the high and low bytes exchange places. Rotate instructions change only CF and (when the count is 1) OF; they do not touch SF, ZF, PF and AF. Shift instructions, however, set SF, ZF and PF according to the result; AF is undefined.
RCL and RCR are the key to multiword shifting. To multiply the 32-bit DX:AX by 2, the low word is shifted first and then the high word is rotated through CF: SHL AX, 1 sends b15 of AX out to CF, and RCL DX, 1 brings this bit into b0 of DX. For example with DX:AX = 0000FFFFh, after these two instructions DX:AX = 0001FFFEh. For division the reverse order is followed: SHR DX, 1 and then RCR AX, 1.
6.7.3Shift count, OF and timing
On the 8086 the shift count is given in only two forms: the constant 1 or the CL register. SHL AX, 1 and SHR AL, CL are valid. A constant greater than 1 such as SHL AL, 4 was added on the 80186 and later processors; in 8086 code one writes SHL AL, 1 four times, or MOV CL, 4 and SHL AL, CL. emu8086 accepts this form, but the code it produces does not run on a real 8086. The 8086 does not mask the number in CL; if CL = 255 the shift is done 255 times. The 80286 and later reduce the count to 5 bits (0–31).
OF is defined for shifts and rotates only when the count is 1. In a one-step left shift, OF says whether the sign bit changed: OF = (new b7) XOR CF. 40h = 0100 0000b shifted left becomes 80h; the sign bit turns from 0 to 1 and OF = 1. C0h shifted left also becomes 80h; but the sign bit stays 1 and OF = 0: −64 × 2 = −128 is correct. When the count is given in CL and is greater than 1, OF is undefined.
In terms of time, shifting is much faster than multiplication. According to Intel's manual, SHL reg, 1 on a register takes 2 clock cycles and SHL reg, CL takes 8 + 4n cycles (n is the shift count). In memory a one-step shift is 15 + EA and with CL 20 + EA + 4n cycles. Considering that a byte MUL takes over 70 cycles, it is understandable why multiplication and division by powers of 2 are left to shifting.
6.7.4Code trace: multiplying by shifting
Processors without a hardware multiplier do multiplication with the method on paper. The bits of the multiplier are examined one by one from right to left. If the bit is 1, the current multiplicand is added to the result; at each step the multiplicand is shifted left by one, that is, multiplied by 2. The program below computes 13 × 5 with this method.
org 100h
mov bl, mcand ; 13
mov dl, mplier ; 5 = 0101b
mov cx, 4 ; 4 bits
check:
shr dl, 1 ; low bit → CF
jnc skip
add result, bl ; add if bit is 1
skip:
shl bl, 1 ; mcand × 2
loop check
ret
mcand db 13
mplier db 5
result db 0There are two control instructions in the program. JNC skip (jump if no carry) goes to the skip label if CF = 0 and skips the addition. LOOP check decrements CX by 1 and returns to the check label if CX is not zero. With CX = 4 the loop runs four times; since the multiplier is 4 bits, this is enough.
| Iteration | DL (after SHR) | CF | Addition | result | BL (after SHL) | CX (after LOOP) |
|---|---|---|---|---|---|---|
| 1 | 02h | 1 | 0 + 0Dh | 0Dh (13) | 1Ah (26) | 3 |
| 2 | 01h | 0 | skipped | 0Dh | 34h (52) | 2 |
| 3 | 00h | 1 | 0Dh + 34h | 41h (65) | 68h (104) | 1 |
| 4 | 00h | 0 | skipped | 41h | D0h | 0 |
The multiplier 5 = 0101b. In the first iteration SHR shifts the rightmost bit (1) out to CF and DL = 02h. Because CF = 1, JNC does not jump; the multiplicand itself, 13 × 1, is added to the result. In the second iteration the bit that comes out is 0 and the addition is skipped. In the third iteration the bit that comes out is 1 again. By then BL has been shifted twice and is 13 × 4 = 52; the result becomes 13 + 52 = 65 = 41h. In the fourth iteration the bit is 0. The loop ends and result = 41h = 65 = 13 × 5 remains. In the last iteration BL has become D0h; this value (208) is no longer used.
The program assumes that the multiplier is 4 bits and that the result fits in a byte. For larger multipliers the loop turns 8 times, and the multiplicand and result are kept in words. In the first generation of microprocessors (Intel 8080, Zilog Z80) there was no multiply instruction and every multiplication was done with a subroutine of this kind. The 8086's MUL instruction also applies the same method inside, in microcode.
6.7.5Fast multiplication and division with shifts
Multiplication by a constant can be turned into shifts and additions according to the binary expansion of that constant. Since 3 = 2 + 1, AX × 3 = AX × 2 + AX:
; AX ← AX × 3 = AX×2 + AX
mov bx, ax ; save
shl ax, 1 ; AX × 2
add ax, bx ; ×2 + ×1
; unsigned ÷ 8 and remainder
mov dx, ax
and dx, 0007h ; rem = low 3 bits
mov cl, 3
shr ax, cl ; quotient
; signed ÷ 4
mov cl, 2
sar ax, cl ; −7 → −2For AX = 25 the first part gives BX = 25, AX = 50 and finally AX = 75. The total time is about 2 + 2 + 3 = 7 cycles; MUL takes over 118. The second part shows division by a power of 2. Shifting right by n bits divides by 2n; the low n bits that go out during the shift are the remainder. The remainder is taken before the shift with AND: the mask with the low three bits 1 is 0007h. For AX = 100 the remainder is DX = 4 and the quotient AX = 12; 12 × 8 + 4 = 100.
The third part divides a signed number with SAR. For AX = −7, SAR gives −2 in two steps; with IDIV, −7 / 4 would give −1. SAR rounds toward minus infinity and IDIV toward zero. When compilers turn signed division into shifting, they first add (2n − 1) to negative numbers to remove this difference.
6.7.6Code trace: 37 × 10 and 370 ÷ 16
Since 10 = 8 + 2, AX × 10 = AX × 8 + AX × 2. The program below first multiplies 37 by 10 this way, then divides the result by 16 and finds the remainder separately.
org 100h
mov ax, 37
shl ax, 1 ; AX × 2
mov bx, ax ; save
shl ax, 1 ; AX × 4
shl ax, 1 ; AX × 8
add ax, bx ; ×8 + ×2
mov bx, ax
and bx, 000Fh ; rem: low 4 bits
mov cl, 4
shr ax, cl ; quotient: ÷ 16
ret| Instruction | Machine code | AX | AX (binary) | BX | CL |
|---|---|---|---|---|---|
mov ax, 37 | B8 25 00 | 0025h = 37 | 0000 0000 0010 0101 | 0000h | 00h |
shl ax, 1 | D1 E0 | 004Ah = 74 | 0000 0000 0100 1010 | 0000h | 00h |
mov bx, ax | 8B D8 | 004Ah | 0000 0000 0100 1010 | 004Ah = 74 | 00h |
shl ax, 1 | D1 E0 | 0094h = 148 | 0000 0000 1001 0100 | 004Ah | 00h |
shl ax, 1 | D1 E0 | 0128h = 296 | 0000 0001 0010 1000 | 004Ah | 00h |
add ax, bx | 03 C3 | 0172h = 370 | 0000 0001 0111 0010 | 004Ah | 00h |
mov bx, ax | 8B D8 | 0172h | 0000 0001 0111 0010 | 0172h | 00h |
and bx, 000Fh | 83 E3 0F | 0172h | 0000 0001 0111 0010 | 0002h | 00h |
mov cl, 4 | B1 04 | 0172h | 0000 0001 0111 0010 | 0002h | 04h |
shr ax, cl | D3 E8 | 0017h = 23 | 0000 0000 0001 0111 | 0002h | 04h |
Each SHL shifts the bits one place left and doubles the number: 37, 74, 148, 296. The ×2 value saved in between (74) is added to the ×8 value and 370 = 37 × 10 is found. For the division, the remainder is separated first: the low four bits of 370 = 0172h are 0010b = 2 and AND BX, 000Fh leaves only them. Then SHR AX, CL shifts four bits right: 0172h → 0017h = 23. Check: 23 × 16 + 2 = 370.
Two details stand out in the machine codes. shl ax, 1 (D1 E0) and shr ax, cl (D3 E8) use different opcodes: D1 means "once", D3 means "CL times". and bx, 000Fh takes three bytes with the 83 form: because the constant 0Fh fits in a single byte, the processor sign-extends it to 16 bits at run time. With the times in Intel's manual the program takes 4 + 2 + 2 + 2 + 2 + 3 + 2 + 4 + 4 + (8 + 4 × 4) = 49 clock cycles; a MUL with a word operand and a DIV together take over 260.
6.8Example: array summation
6.8.1The program
Adding two arrays element by element and writing the result to a third array is the simplest example in which arithmetic instructions are used together with memory. The program below does vec3[i] = vec1[i] + vec2[i] for i = 0…3.
org 100h
jmp start
vec1 db 1, 2, 5, 6
vec2 db 3, 5, 6, 1
vec3 db ?, ?, ?, ?
start:
lea si, vec1
lea bx, vec2
lea di, vec3
mov cx, 4
sum:
mov al, [si]
add al, [bx]
mov [di], al
inc si
inc bx
inc di
loop sum
retThe structure of the program, line by line, is as follows.
JMP startjumps over the data definitions. In a .COM program code and data are in the same segment and execution starts at 0100h. Without the jump the processor would try to decode the bytes of vec1 (01 02 05 06) as instructions.vec3 db ?, ?, ?, ?reserves four bytes. The question mark means "the initial value does not matter"; emu8086 writes 0 to these bytes.LEA(load effective address) loads not the value of a variable but its address (offset). SI, BX and DI become the pointers of the three arrays.MOV AL, [SI]reads the memory byte SI points to; this is register indirect addressing.ADD AL, [BX]adds the element of the second array, andMOV [DI], ALwrites the result to the third array.- The three INCs advance the pointers to the next element. Because the arrays are byte arrays each pointer increases by 1; with word arrays it would have to increase by 2.
LOOP sumbuilds the loop.
The LOOP instruction always uses CX as the loop counter. Each time it executes it first decrements CX by 1 and then looks at CX. If CX is nonzero it jumps back to the label (sum); if zero it goes on to the next instruction (RET). Because CX was loaded with 4 before the loop, the body runs four times: after LOOP, CX becomes 3, 2, 1 and 0 in turn and on the last time the jump is not taken. LOOP does not change the flags. On the 8086 a LOOP that jumps takes 17 clock cycles and one that does not takes 5.
6.8.2Code trace
| Step | SI | BX | DI | CX | AL | vec3 | Explanation |
|---|---|---|---|---|---|---|---|
jmp start | 0000h | 0000h | 0000h | 0000h | 00h | 0 0 0 0 | the data (0102h–010Dh) is skipped |
lea si / bx / di | 0102h | 0106h | 010Ah | 0000h | 00h | 0 0 0 0 | the addresses of the three arrays |
mov cx, 4 | 0102h | 0106h | 010Ah | 0004h | 00h | 0 0 0 0 | 4 iterations |
iteration 1: mov al,[si] · add al,[bx] | 0102h | 0106h | 010Ah | 0004h | 04h | 0 0 0 0 | 1 + 3 = 4 |
iteration 1: mov [di],al | 0102h | 0106h | 010Ah | 0004h | 04h | 4 0 0 0 | vec3[0] = 4 |
iteration 1: three inc · loop | 0103h | 0107h | 010Bh | 0003h | 04h | 4 0 0 0 | CX = 3 ≠ 0 → back to sum |
| iteration 2 | 0104h | 0108h | 010Ch | 0002h | 07h | 4 7 0 0 | 2 + 5 = 7 |
| iteration 3 | 0105h | 0109h | 010Dh | 0001h | 0Bh | 4 7 11 0 | 5 + 6 = 11 |
| iteration 4 | 0106h | 010Ah | 010Eh | 0000h | 07h | 4 7 11 7 | 6 + 1 = 7; CX = 0, the loop ends |
After the last iteration the pointers point one element past the arrays. SI = 0106h is now the first element of vec2; BX = 010Ah is the first element of vec3. This is the natural consequence of the arrays lying one after another in memory, and it is harmless since the loop has ended. Because the sums do not exceed 255, CF is never 1 in any iteration; with large elements the sum may not fit in a byte, and then CF must be looked at after the ADD.
6.8.3Program and data in memory
Table 6.30 gives the view of the program in the emu8086 memory window (CS = DS = 0700h). Code and data are in the same segment, one after another.
| Address | Bytes | Meaning |
|---|---|---|
| 0100h | EB 0C | JMP 010Eh; target = 0102h + 0Ch |
| 0102h | 01 02 05 06 | vec1 (data) |
| 0106h | 03 05 06 01 | vec2 (data) |
| 010Ah | 04 07 0B 07 | vec3 (after the program has run) |
| 010Eh | BE 02 01 | MOV SI, 0102h (the code of LEA) |
| 0111h | BB 06 01 | MOV BX, 0106h |
| 0114h | BF 0A 01 | MOV DI, 010Ah |
| 0117h | B9 04 00 | MOV CX, 0004h; the constant is little-endian |
| 011Ah | 8A 04 | MOV AL, [SI] (sum:) |
| 011Ch | 02 07 | ADD AL, [BX] |
| 011Eh | 88 05 | MOV [DI], AL |
| 0120h | 46 43 47 | INC SI, INC BX, INC DI (one byte each) |
| 0123h | E2 F5 | LOOP 011Ah; F5h = −11 |
| 0125h | C3 | RET |
Three things can be read from the table. First, emu8086 turns the directly addressed LEA SI, vec1 line into the same three-byte code as MOV SI, 0102h. The two instructions do the same job: because the offset of the variable is known at assembly time, it is enough to load it as a constant. MASM, however, produces LEA with its own opcode (8D 36 02 01) as four bytes; in that case the following addresses shift by one byte. Second, jump instructions carry not the target address but the distance relative to the next instruction. The distance of JMP is 0Ch: 0102h + 0Ch = 010Eh. The distance of LOOP is F5h; as a signed number it is −11 and takes control back to 0125h − 0Bh = 011Ah, that is, to the sum label. Third, the constant in the MOV CX, 4 instruction sits in memory with the low byte first, as 04 00.
6.9BCD arithmetic
6.9.1Binary-coded decimal numbers
People think in decimal, while the processor computes in binary. In devices that show decimal digits directly, such as calculators, cash register software, clock chips and seven-segment displays, converting the number from binary to decimal every time is expensive. Instead the number can be stored digit by digit.
In binary-coded decimal (BCD) representation each decimal digit is held in a separate 4-bit group with the values 0000–1001; 1010–1111 are not used. Unpacked BCD puts one digit in each byte; the upper nibble is 0. Packed BCD puts two digits in a byte: the high nibble is the tens digit and the low nibble the ones digit.
| Representation | Bits | Byte(s) |
|---|---|---|
| Binary | 0000 1110 | 0Eh |
| Unpacked BCD | 0000 0001 · 0000 0100 | 01h 04h (AH, AL) |
| Packed BCD | 0001 0100 | 14h |
| ASCII | 0011 0001 · 0011 0100 | 31h 34h ('1', '4') |
In packed BCD the number 14 is written as the byte 14h; the hexadecimal notation reads the decimal digits directly. ASCII digits are unpacked BCD with 3 added to the high nibble. Thanks to this closeness, digits read from the keyboard become unpacked BCD with AND 0Fh, and unpacked BCD becomes a character to write on the screen with OR 30h.
The processor's adder does not know BCD; it adds two BCD numbers like binary numbers. The result is often an incorrect BCD. 9 + 5 gives 0Eh in binary; the correct BCD result is "14". The 8086 therefore offers BCD adjust instructions that convert the result into BCD after a binary operation. All of them work only on AL (and AH when needed); BCD arithmetic is therefore done byte by byte.
6.9.2The adjust instructions
| Instruction | When | Effect | Time (cycles) |
|---|---|---|---|
AAA | after unpacked addition | adjusts AL to BCD, carry into AH | 4 |
AAS | after unpacked subtraction | adjusts AL, borrow from AH | 4 |
AAM | after unpacked multiplication | AH ← AL / 10, AL ← AL mod 10 | 83 |
AAD | before unpacked division | AL ← AH × 10 + AL, AH ← 0 | 60 |
DAA | after packed addition | adjusts the two digits in AL | 4 |
DAS | after packed subtraction | adjusts the two digits in AL | 4 |
The idea of the adjustment rests on the number 6. A nibble can take 16 values while a decimal digit takes 10. When the sum of a digit exceeds 9, the binary sum falls 6 short of BCD: 9 + 5 = 0Eh, whereas "14" = 14h = 0Eh + 6. If the digit sum exceeds 15 (for example 9 + 8 = 17), a carry comes out of the nibble and AF = 1; in this case too 6 must be added: 9 + 8 = 11h, 11h + 6 = 17h. The adjust instructions check these two conditions (nibble value > 9 or AF = 1) and add or subtract 6 if needed.
AAA: if the low nibble of AL is greater than 9 or AF = 1, 6 is added to AL, 1 is added to AH and AF = CF = 1; otherwise AF = CF = 0. In both cases the high nibble of AL is cleared. AAS makes the same check, but subtracts 6 from AL and 1 from AH.
DAA: First the low nibble is checked: if it is greater than 9 or AF = 1, 06h is added to AL and AF = 1. Then the high digit is checked: if AL before the operation was greater than 99h or CF = 1, 60h is added to AL and CF = 1. DAS subtracts 06h and 60h with the same checks.
The application of the rules is seen in a few examples. 38h + 45h = 7Dh; because the low nibble D > 9, DAA adds 06h and AL = 83h: 38 + 45 = 83. 99h + 01h = 9Ah; the low nibble A > 9, AL + 06h = A0h; because the original AL was greater than 99h, 60h is added too and AL = 00h, CF = 1: 99 + 1 = 100, "00" and the hundreds digit in CF. In subtraction 83h − 38h = 4Bh; because the low nibble B > 9, DAS subtracts 06h and AL = 45h: 83 − 38 = 45. 25h − 48h = DDh; both adjustments are needed and DAS gives AL = 77h, CF = 1. This reads like 125 − 48 = 77: CF = 1 says a borrow was taken from the high digit.
6.9.3Code trace: 9 + 5 with AAA
The following program adds two unpacked BCD digits, adjusts the result with AAA and prints the two digits on the screen. The printing part uses the 0Eh service (teletype) of BIOS interrupt 10h: with AH = 0Eh, INT 10h writes the character in AL where the cursor is and advances the cursor by one.
; first number '9':
mov ah, 09h
; second number '5':
mov al, 05h
; al = al + ah = 09h + 05h = 0eh
add al, ah
; clear tens byte of bcd
xor ah, ah
; adjust result to bcd form, ah = 1, al = 4 -> '14'
aaa
; --- print the result (extra) ---
or ax, 3030h ; to ASCII
mov bl, al ; save '4'
mov al, ah ; '1'
mov ah, 0Eh
int 10h
mov al, bl
int 10h
ret| Instruction | Machine code | AX | BL | CF | AF | Explanation |
|---|---|---|---|---|---|---|
mov ah, 09h · mov al, 05h | B4 09 · B0 05 | 0905h | 00h | 0 | 0 | two digits |
add al, ah | 02 C4 | 090Eh | 00h | 0 | 0 | 9 + 5 = 0Eh; right in binary, not BCD |
xor ah, ah | 32 E4 | 000Eh | 00h | 0 | ? | the tens digit is cleared |
aaa | 37 | 0104h | 00h | 1 | 1 | E > 9: AL + 6 = 14h, AH + 1, the high nibble is cleared |
or ax, 3030h | 0D 30 30 | 3134h | 00h | 0 | ? | '1', '4' |
mov bl, al · mov al, ah | 8A D8 · 8A C4 | 3131h | 34h | 0 | ? | '4' saved, AL = '1' |
mov ah, 0Eh · int 10h | B4 0E · CD 10 | 0E31h | 34h | 0 | ? | '1' on the screen |
mov al, bl · int 10h | 8A C3 · CD 10 | 0E34h | 34h | 0 | ? | '4' on the screen |
09h + 05h = 0Eh, which in binary is 14 and is correct; but in BCD there is no digit E. When 9 + 5 was added in the low nibbles, no carry came out of bit 3, AF = 0. AAA sees that the low nibble E > 9. It adds 6 to AL: 0Eh + 6 = 14h. It increments AH by 1, sets AF and CF to 1, and clears the high nibble of AL: AL = 04h. The result is AX = 0104h, that is, unpacked "14". OR AX, 3030h puts 3 in the high nibbles of the two bytes and AX = 3134h, the ASCII '1' and '4'. The rest of the program writes these two characters to the screen in turn.
The purpose of the XOR AH, AH line is to have AAA write its carry into a clean tens digit. Without this line the first digit (09h) would remain in AH and AAA would make it 0Ah. AAA looks only at the low nibble of AL; so it is not necessary to subtract 30h from ASCII digits before the addition. In '7' + '8' = 37h + 38h = 6Fh the low nibble F > 9; AAA gives AH = 01h, AL = 05h, and with OR AX, 3030h '1' and '5' are obtained.
6.9.4Code trace: 5 − 8 with AAS
; make 5 - 8, al = 0fdh (not in bcd form)
mov al, 05h
mov bl, 08h
sub al, bl
; convert to bcd, al = 7
; and 1 is borrowed from ah,
; like calculating 15 - 8:
aas
; --- print ---
or al, 30h
mov ah, 0Eh
int 10h
mov ah, 0
int 16h
ret| Instruction | AX | BL | CF | AF | SF | Explanation |
|---|---|---|---|---|---|---|
mov al, 05h · mov bl, 08h | 0005h | 08h | 0 | 0 | 0 | |
sub al, bl | 00FDh | 08h | 1 | 1 | 1 | 5 − 8 = −3 = FDh |
aas | FF07h | 08h | 1 | 1 | ? | AL − 6 = F7h, AH − 1 = FFh; the high nibble is cleared |
or al, 30h | FF37h | 08h | 0 | ? | 0 | AL = '7' |
mov ah, 0Eh · int 10h | 0E37h | 08h | 0 | ? | 0 | '7' on the screen |
mov ah, 0 · int 16h | — | 08h | 0 | ? | 0 | waits for a key; AL = the code of the key pressed |
5 − 8 = −3, which is FDh in two's complement. A borrow was taken (CF = 1); in the low nibble too 5 − 8 needed a borrow (AF = 1). Because AF = 1, AAS subtracts 6 from AL: FDh − 6 = F7h. It borrows 1 from AH: 00h − 1 = FFh. It clears the high nibble of AL: AL = 07h. The result is AX = FF07h. "7" appears on the screen.
This result looks odd at first: 5 − 8 should be −3. What AAS does is take a 10 from a higher digit, as in subtraction on paper: 15 − 8 = 7. CF = 1 says that a borrow was taken and that the result is negative. 7 is the ten's complement of −3 (10 − 3 = 7). In a multidigit BCD subtraction this borrow is paid with SBB in the subtraction of the next digit; that AH is FFh reflects this. If we had started with AH = 01h (unpacked "15"), AAS would have given AX = 0007h, that is, the correct "07".
6.9.5AAM and AAD
The adjustment for multiplication and division works differently from that for addition, because adding 6 is not enough here; the number must really be divided by 10 or multiplied by 10. The 8086 offers two instructions that do these two jobs in microcode.
AAM (ASCII adjust after multiply) divides AL by 10: the quotient is written to AH and the remainder to AL. It splits the product of two unpacked digits (at most 9 × 9 = 81) into two unpacked digits. AAD (ASCII adjust before division) converts the tens digit in AH and the ones digit in AL to a binary number: AL ← AH × 10 + AL, AH ← 0. It is written before a division instruction. Both set SF, ZF and PF according to AL; OF, AF and CF are undefined.
mov al, 7
mov bl, 8
mul bl ; AX = 0038h (56)
aam ; AH = 05h, AL = 06h
mov ax, 0504h ; '54' unpacked
aad ; AX = 0036h (54)
mov bl, 6
div bl ; AL = 09h, AH = 00hIn the first part 7 × 8 = 56 = 0038h. AAM divides 56 by 10: AH = 5, AL = 6. AX = 0506h is now unpacked "56". In the second part AX = 0504h is unpacked "54". AAD converts it to 5 × 10 + 4 = 54 = 36h and zeroes AH. With a normal DIV, 54 / 6 = 9: AL = 09h, remainder AH = 00h. If AAD had been forgotten, DIV would have divided 0504h = 1284 and the result would have been 1284 / 6 = 214.
The machine code of AAM and AAD is interesting: D4 0A and D5 0A. The second byte is 0Ah, that is 10. On the 8086 this byte is really used as the base; D4 10 divides AL by 16. Intel did not document this, and assemblers always produce 0Ah. D4 00 raises INT 0 because it is a division by zero. AAM takes 83 and AAD 60 clock cycles; they are a division and a multiplication done in microcode.
6.9.6Code trace: AAM, AAD and DAA
MOV AL, 6
MOV BL, 9
MUL BL ; AX = 6 × 9
AAM ; split digits
MOV AX, 0702h ; '72' unpacked
AAD ; to binary
MOV BL, 8
DIV BL
MOV AL, 19h ; packed 19
ADD AL, 28h ; + 28
DAA ; adjust BCD
RET| Instruction | Machine code | AX | BL | AF | CF | Explanation |
|---|---|---|---|---|---|---|
MOV AL, 6 · MOV BL, 9 | B0 06 · B3 09 | 0006h | 09h | 0 | 0 | |
MUL BL | F6 E3 | 0036h | 09h | ? | 0 | 6 × 9 = 54; fits in AL |
AAM | D4 0A | 0504h | 09h | ? | ? | unpacked "54" |
MOV AX, 0702h | B8 02 07 | 0702h | 09h | ? | ? | unpacked "72" |
AAD | D5 0A | 0048h | 09h | ? | ? | 7 × 10 + 2 = 72 = 48h |
MOV BL, 8 · DIV BL | B3 08 · F6 F3 | 0009h | 08h | ? | ? | 72 / 8 = 9, remainder 0 |
MOV AL, 19h | B0 19 | 0019h | 08h | ? | ? | packed "19" |
ADD AL, 28h | 04 28 | 0041h | 08h | 1 | 0 | 9 + 8 = 17: carry out of the nibble |
DAA | 27 | 0047h | 08h | 1 | 0 | AF = 1 → AL + 06h = 47h |
The last three lines of the program show why DAA needs AF. 19h + 28h = 41h. The low nibble of the result is 1 and is not greater than 9; looking at it alone, no adjustment seems necessary. But in the ones digit 9 + 8 = 17 occurred and a carry came out of the nibble: AF = 1. DAA sees this flag and adds 06h: 41h + 06h = 47h. The result is "47" = 19 + 28. Because the high nibble 4 ≤ 9 and CF = 0, the second adjustment is not made.
Not writing the adjust instruction right after the addition. DAA and AAA look at AF and CF; a MOV in between causes no problem, but an instruction that changes the flags (ADD, CMP, AND, even an INC, which changes AF) spoils the adjustment. Another mistake is to use AAA with packed BCD or DAA with unpacked BCD: AAA clears the high nibble and destroys the tens digit of a packed number.
6.10Example: temperature conversion
6.10.1Celsius to Fahrenheit
The relation between degrees Celsius (°C) and degrees Fahrenheit (°F) is f = c × 9 / 5 + 32. The program below computes this formula with integer operations. Because temperatures can be negative, signed instructions (IMUL, IDIV) are used.
org 100h
start:
;celsius to fahrenheit according to f = c * 9 / 5 + 32
mov cl, 15
mov al, 9
imul cl
mov cl, 5
idiv cl
add al, 32
ret| Instruction | Machine code | AX | CL | CF | OF | Explanation |
|---|---|---|---|---|---|---|
mov cl, 15 | B1 0F | 0000h | 0Fh | 0 | 0 | c = 15 |
mov al, 9 | B0 09 | 0009h | 0Fh | 0 | 0 | |
imul cl | F6 E9 | 0087h | 0Fh | 1 | 1 | 9 × 15 = 135; does not fit a signed byte, but is complete in AX |
mov cl, 5 | B1 05 | 0087h | 05h | 1 | 1 | divisor |
idiv cl | F6 F9 | 001Bh | 05h | ? | ? | 135 / 5 = 27, remainder 0 |
add al, 32 | 04 20 | 003Bh | 05h | 0 | 0 | 27 + 32 = 59 |
9 × 15 = 135. 135 does not fit a signed byte (at most 127); IMUL therefore sets CF = OF = 1. But this is not an error: the result sits complete in AX as 0087h. IDIV divides AX by 5; the quotient 27 = 1Bh is written to AL and the remainder 0 to AH. 27 + 32 = 59 = 3Bh: 15 °C = 59 °F. When the program ends AX = 003Bh and CX = 0005h.
The order of operations in the formula matters. First multiply by 9, then divide by 5. If it were done the other way round, that is, 9 / 5 computed first, integer division would give 1 and the wrong formula f = c + 32 would result. In integer arithmetic division is left to the end as far as possible.
6.10.2Fahrenheit to Celsius
org 100h
start:
;fahrenheit to celsius according to: c = (f - 32) * 5 / 9
mov cl, 59
sub cl, 32
mov al, 5
imul cl
mov cl, 9
idiv cl
ret| Instruction | Machine code | AX | CL | CF | OF | Explanation |
|---|---|---|---|---|---|---|
mov cl, 59 | B1 3B | 0000h | 3Bh | 0 | 0 | f = 59 |
sub cl, 32 | 80 E9 20 | 0000h | 1Bh | 0 | 0 | 59 − 32 = 27 |
mov al, 5 | B0 05 | 0005h | 1Bh | 0 | 0 | |
imul cl | F6 E9 | 0087h | 1Bh | 1 | 1 | 5 × 27 = 135 |
mov cl, 9 · idiv cl | B1 09 · F6 F9 | 000Fh | 09h | ? | ? | 135 / 9 = 15, remainder 0 |
59 − 32 = 27, 5 × 27 = 135 and 135 / 9 = 15: 59 °F = 15 °C. The result is in AL; AH carries the remainder (0). The two programs are inverses of each other and go back and forth exactly between 15 and 59, because the remainder is zero in both divisions.
6.10.3Why IMUL and IDIV? The limits
Negative temperatures are the reason for the signed instructions. For c = −10, IMUL reads −10 = F6h as signed and gives AX = FFA6h = −90. IDIV computes −90 / 5 = −18 = EEh; with 32 added, 0Eh = 14: −10 °C = 14 °F is correct. If the same calculation were done with MUL and DIV, F6h would be taken as 246. MUL gives 9 × 246 = 2214 = 08A6h, and when DIV divides this number by 5 the quotient 442 does not fit in AL: the program stops with a divide error.
Integer division throws away the fractional part. Because IDIV truncates toward zero, c = 1 °C gives 33 °F with 9 / 5 = 1; the correct value is 33.8. If rounding is needed, the remainder in AH is examined: if the remainder is greater than half of the divisor, 1 is added to the quotient.
The most important limit of the program is that the result is kept in AL, a signed byte. Table 6.38 shows the limits of the Celsius to Fahrenheit conversion with numbers.
| c | IMUL: AX | IDIV: AL | AL after ADD | OF | Result |
|---|---|---|---|---|---|
| −72 | FD78h (−648) | quotient −129 does not fit → INT 0 | divide error | ||
| −71 | FD81h (−639) | 81h (−127) | A1h (−95) | 0 | correct |
| −10 | FFA6h (−90) | EEh (−18) | 0Eh (14) | 0 | correct |
| 53 | 01DDh (477) | 5Fh (95) | 7Fh (127) | 0 | correct (the largest) |
| 54 | 01E6h (486) | 61h (97) | 81h | 1 | wrong: read as −127 |
| 72 | 0288h (648) | quotient 129 does not fit → INT 0 | divide error | ||
The valid range is c ∈ [−71, 53]. At c = 54 the quotient 97 fits, but 97 + 32 = 129 does not fit a signed byte; ADD sets OF = 1 and AL = 81h, read as −127. At c = 72 the quotient itself (129) does not fit in AL and a divide error occurs. In the Fahrenheit to Celsius conversion the limit is that f − 32 must fit in a byte: f ∈ [−96, 127]. For wider ranges, word operations are needed: c is taken into AX and multiplied in 16 bits with IMUL BX. Because the product is already in DX:AX, CWD is not needed; it is divided directly with IDIV.
6.11Which instruction affects which flag?
Table 6.39 collects the flag effect of all the instructions described in these notes in one table. When tracing a program, or when looking for why a conditional jump behaves unexpectedly, this is the first place to look.
| Instruction | CF | ZF | SF | OF | PF | AF |
|---|---|---|---|---|---|---|
ADD SUB CMP ADC SBB | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
NEG | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
INC DEC | — | ✓ | ✓ | ✓ | ✓ | ✓ |
AND OR XOR TEST | 0 | ✓ | ✓ | 0 | ✓ | ? |
NOT | — | — | — | — | — | — |
MUL IMUL | ✓ | ? | ? | ✓ | ? | ? |
DIV IDIV | ? | ? | ? | ? | ? | ? |
SHL SHR SAR | ✓ | ✓ | ✓ | ✓¹ | ✓ | ? |
ROL ROR RCL RCR | ✓ | — | — | ✓¹ | — | — |
AAA AAS | ✓ | ? | ? | ? | ? | ✓ |
AAM AAD | ? | ✓ | ✓ | ? | ✓ | ? |
DAA DAS | ✓ | ✓ | ✓ | ? | ✓ | ✓ |
CBW CWD MOV LEA LOOP | — | — | — | — | — | — |
The table can be reduced to a few general rules. Data movement instructions (MOV, LEA, XCHG, CBW, CWD) and LOOP do not touch the flags. The addition and subtraction family writes all the flags; INC and DEC preserve CF of these. Logic instructions clear CF and OF. Multiplication writes a meaningful value only to CF and OF, and division to no flag. Rotates change only CF and OF. A program that relies on an undefined flag may work on one processor and break on another.
6.12Common mistakes
| Mistake | What happens? | Correct |
|---|---|---|
| Looking at CF with signed numbers | correct results such as −1 + 1 are taken as "overflowed" | signed: OF; in comparisons SF ≠ OF |
Forgetting DX before DIV BX | the old DX enlarges the dividend; wrong result or INT 0 | XOR DX, DX or CWD |
MOV AH, 0 for a signed byte | −30 = E2h is counted as 226 | CBW |
MUL 10 | the 8086 has no immediate operand; the assembler rejects it | MOV BL, 10 · MUL BL |
SHL AX, 4 | an 80186 instruction; does not work on the 8086 | MOV CL, 4 · SHL AX, CL |
| ADD on both words | the carry of the low word is lost | ADD, then ADC |
| A CMP between ADD and ADC | CF is erased | only MOV, INC, DEC, LOOP in between |
| AND to test a bit | the other bits of the number are erased | TEST |
| Dividing a negative number with SAR and expecting the IDIV result | −7 / 2: SAR −4, IDIV −3 | choosing the rounding direction knowingly |
| Writing AAD after DIV | the unpacked number is taken for binary: 0702h = 1794 is divided | AAD before the division |
Choosing the wrong operand size for MUL and IMUL. MUL BX is a word multiplication and writes the result to DX:AX; a value kept in DX is silently erased. If a byte multiplication is wanted the operand must be 8 bits (MUL BL); then only AX changes.
6.13Exercises and solutions
The eleven exercises in the slides are solved here with their intermediate steps.
1. What are AL, CF, OF, SF, ZF, PF after MOV AL, 0C0h and ADD AL, 0C0h?
C0h + C0h = 180h; AL = 80h, CF = 1. −64 + (−64) = −128 fits a signed byte: OF = 0. SF = 1, ZF = 0. 80h has a single 1 bit: PF = 0.
2. After CMP AL, BL, by which flag is unsigned "AL < BL" recognized, and by which flags signed "AL < BL"?
Unsigned: CF = 1 (the subtraction needed a borrow); JB tests this. Signed: SF ≠ OF; JL tests this. SF alone is not enough, because if the difference overflows the sign bit flips.
3. With AX = 0FFFFh, BX = 0FFFFh, what are DX, AX, CF after MUL BX?
65,535² = 4,294,836,225 = FFFE0001h. DX = FFFEh, AX = 0001h. Since the upper half is not zero, CF = OF = 1.
4. What happens with AX = 0100h, BL = 0 on DIV BL?
Division by zero: the processor raises INT 0 (divide error). AX and the flags do not change; control passes to the interrupt service routine.
5. Change the array summation program for word (DW) arrays.
The data are defined with dw, AX is used instead of AL, and the pointers advance by 2:
vec1 dw 1000, 2000, 3000, 4000
vec2 dw 5, 6, 7, 8
vec3 dw 4 dup(?)
; ...
sum:
mov ax, [si]
add ax, [bx]
mov [di], ax
add si, 2
add bx, 2
add di, 2
loop sumWith this data vec3 = 1005, 2006, 3007, 4008. INC SI can be written twice; but ADD SI, 2 changes CF and INC does not. If the loop uses ADC, the INCs are preferred.
6. Write the program that counts the 1 bits in a byte with SHL/TEST and a loop. Compare with PF.
mov al, 0B5h ; the byte to count
xor bl, bl ; counter
mov cx, 8
again:
test al, 80h ; is the leftmost bit 1?
jz zero
inc bl
zero:
shl al, 1
loop againFor B5h = 1011 0101b, BL = 5. In each iteration TEST tests the leftmost bit and SHL brings the next bit to the far left. JZ (jump if ZF = 1) skips incrementing the counter if the bit is 0. PF says only whether the number of 1s is odd or even: for B5h PF = 0 (five is odd), but it does not give how many 1s there are.
7. What happens with DX = 0005h, AX = 0000h, BX = 0005h on DIV BX?
The dividend DX:AX = 50000h = 327,680. The quotient would be 65,536 and does not fit in AX. The rule says so too: DX = 5 ≥ the divisor 5. Even though the divisor is not zero, a divide error (INT 0) occurs.
8. What are AL and OF after MOV AL, 70h and ADD AL, 30h? How is the correct sum obtained in 16 bits?
AL = A0h, OF = 1: 112 + 48 = 160 > 127. The two numbers are extended separately with CBW and added in 16 bits: MOV AL, 70h · CBW · MOV DX, AX · MOV AL, 30h · CBW · ADD AX, DX → AX = 00A0h = 160.
9. Do 00012345h − 0000ABCDh with SUB/SBB. What is CF after the SUB?
2345h − ABCDh = 7778h, CF = 1 (borrow). 0001h − 0000h − 1 = 0000h. The result is 00007778h = 30,584.
10. In the 32 × 32-bit multiplication, to which words of the result are the four partial products added?
A0·B0 → z1:z0; A1·B0 and A0·B1 → z2:z1; A1·B1 → z3:z2. The carry of each ADD is carried to the next word up with ADC; after the third partial product an ADC [z+6], 0 that adds only the carry to z3 may be needed.
11. With DX = 0000h, AX = 0FFFh, CF = 0, what is DX:AX after SHL AX, 1 and RCL DX, 1?
SHL: AX = 1FFEh, the bit that came out (b15 = 0) goes to CF: CF = 0. RCL: 0 enters DX, DX = 0000h. DX:AX = 00001FFEh = 0FFFh × 2.
6.14Summary
- Flags: arithmetic and logic instructions write the result to the destination and the properties of the result to the flags register. CF shows unsigned overflow (a carry in addition, a borrow in subtraction), OF shows signed overflow; OF = the XOR of the carries into and out of the most significant bit. ZF result zero, SF most significant bit, PF an even number of 1s in the low byte, AF carry from bit 3.
- Two-operand instructions (ADD, ADC, SUB, SBB, CMP, AND, OR, XOR, TEST) write the result to the destination; CMP and TEST change only the flags. Two memory operands, different sizes, a constant destination and a segment register cannot be used. Register-register takes 3 clock cycles, memory destination 16 + EA.
- Comparison: after CMP, unsigned "below" is CF = 1, signed "less" is SF ≠ OF.
- Multiword arithmetic: ADD/SUB on the lowest word, ADC/SBB on the upper ones; the carry is carried in CF. A 32 × 32 multiplication is done with four MULs and a chain of ADD/ADC.
- Logic instructions work bit by bit; they make CF = OF = 0. AND clears bits, OR sets them, XOR inverts them, TEST tests them. NOT changes no flag.
- Multiplication and division: in byte operations AX = AL × operand, AL = AX / operand (AH remainder); in word operations DX:AX. MUL/IMUL set only CF = OF meaningfully; DIV/IDIV leave all flags undefined. INT 0 if the divisor is 0 or the quotient does not fit. IDIV truncates toward zero.
- Sign extension: CBW (AL → AX) and CWD (AX → DX:AX) before signed division and signed addition; for unsigned data the upper half is zeroed.
- INC and DEC preserve CF; NEG takes the two's complement and sets CF = 1 if the operand is nonzero; NEG 80h overflows.
- Shifts and rotates: the count is 1 or CL. SHL ×2, SHR unsigned ÷2, SAR signed ÷2 (rounds toward minus infinity). In a rotate no bit is lost; RCL/RCR form a 9- or 17-bit ring with CF and make multiword shifting possible. Multiplying with shifts is much faster than MUL.
- BCD: AAA/AAS after unpacked addition/subtraction, DAA/DAS after packed addition/subtraction, AAM after multiplication, AAD before division. The adjustment rests on adding or subtracting 6 (and 60h for packed); this is why AF exists.
- Application: array summation is done with LOOP, temperature conversion with IMUL/IDIV; a signed byte result is correct only within a certain range.
6.15Key terms
- arithmetic logic unit (ALU)
- execution unit (EU)
- flags register (FLAGS)
- status / control flag
- carry flag (CF)
- overflow flag (OF)
- zero, sign, parity flag
- auxiliary carry flag (AF)
- carry / borrow
- signed / unsigned number
- two's / one's complement
- arithmetic / logical instruction
- implicit operand
- masking
- multiplication / division
- dividend / divisor / quotient / remainder
- sign extension
- shift / rotate
- logical / arithmetic shift
- binary-coded decimal (BCD)
- packed / unpacked BCD
- BCD adjustment
- nibble
- loop
- conditional jump
- interrupt vector
- microcode
- clock cycle
- bus cycle
6.16Test Yourself
What are AL and the six status flags after
MOV AL, 9ChandADD AL, 9Ch?Answer
9Ch + 9Ch = 138h; AL = 38h, CF = 1. Signed −100 + (−100) = −200 does not fit a byte and the sum of two negatives has come out positive (38h): OF = 1. SF = 0, ZF = 0. 38h = 0011 1000b has three 1s: PF = 0. The low nibbles are C + C = 18h; a carry comes out of bit 3: AF = 1.
What CF and OF values does
SUB AL, BLgive for AL = 30h, BL = 50h, and for AL = 80h, BL = 01h?Answer
30h − 50h = E0h: unsigned 48 − 80 needs a borrow, CF = 1; signed 48 − 80 = −32 is correct, OF = 0. 80h − 01h = 7Fh: unsigned 128 − 1 = 127 is correct, CF = 0; signed −128 − 1 = −129 does not fit and a negative has turned into a positive, OF = 1.
With AL = F0h, BL = 10h, what are AX and CF after
IMUL BLand afterMUL BL? What would IMUL give if AL = F8h?Answer
IMUL: −16 × 16 = −256 = FF00h; −256 does not fit a byte, CF = OF = 1. MUL: 240 × 16 = 3840 = 0F00h; AH ≠ 0, CF = 1. For AL = F8h (−8) IMUL gives −128 = FF80h; AH is only the sign extension of AL and CF = OF = 0.
The number −50 is divided by 7 and by 8 with IDIV (AX = −50). What are the quotients and remainders? What is found if −50 is shifted 3 bits with SAR?
Answer
IDIV 7: −50 / 7 = −7.14; toward zero −7 = F9h, remainder −50 − (−49) = −1 = FFh. IDIV 8: quotient −6 = FAh, remainder −2 = FEh. SAR 3 (÷ 8): CEh = 1100 1110b → 1111 1001b = F9h = −7; −6.25 has been rounded toward minus infinity to −7. IDIV and SAR give different results.
With CF = 1 and AL = 81h, what are AL and CF after three consecutive
RCL AL, 1instructions?Answer
1000 0001b, CF = 1 → 0000 0011b, CF = 1 → 0000 0111b, CF = 0 → 0000 1110b, CF = 0. AL = 0Eh, CF = 0. The bits have turned around the nine-bit ring and none has been lost.
58 + 67 is done in packed BCD:
MOV AL, 58h,ADD AL, 67h,DAA. What are AL, AF and CF after the ADD and after the DAA?Answer
ADD: 58h + 67h = BFh; in the low nibble 8 + 7 = 15 = Fh, no carry (AF = 0), CF = 0. DAA: low nibble F > 9 → +06h = C5h, AF = 1; the original AL BFh > 99h → +60h = 125h, AL = 25h, CF = 1. The result is "25" and 1 in the hundreds digit: 58 + 67 = 125.
With AL = B6h, what are AL and PF after
AND AL, 0F0h,OR AL, 05h,XOR AL, 0FFh?Answer
AND: B0h (the low nibble is cleared). OR: B5h (bits 0 and 2 are set). XOR: 4Ah = 0100 1010b (all bits are inverted). There are three 1s: PF = 0. After logic instructions CF = OF = 0.
Which three instructions are written to add 1 to the 48-bit number DX:BX:AX = 0001 FFFF FFFFh? What is the result?
Answer
ADD AX, 1·ADC BX, 0·ADC DX, 0. AX = 0000h and CF = 1; BX = FFFFh + 0 + 1 = 0000h and CF = 1; DX = 0001h + 0 + 1 = 0002h. The result is 0002 0000 0000h. IfINC AXhad been used, CF would not have changed and the carry would have been lost.What are AX, CF and OF after
MOV AX, 8000handNEG AX? Why?Answer
AX stays 8000h; CF = 1 (the operand is not zero), OF = 1. 8000h is −32,768 as a signed word; +32,768 does not fit the word range (at most 32,767). NOT 8000h = 7FFFh, +1 = 8000h.
What is the difference between
INC AXandADD AX, 1in machine code, time and flags?Answer
INC AXis a single byte (40) and takes 2 clock cycles; it does not touch CF.ADD AX, 1is three bytes (05 01 00, or three bytes with the 83 form as well) and takes 4 cycles; it writes six flags including CF. With AX = FFFFh, ADD sets CF = 1; INC leaves CF as it was.
6.17Further reading
- B. B. Brey, The Intel Microprocessors (8th ed.), Chapter 5: arithmetic and logic instructions, BCD and ASCII adjustments, shifts and rotates; it extends the subjects of these notes to the processors after the 8086.
- Intel, The 8086 Family User's Manual (1979), the instruction set section: the flag effect, encoding and clock cycle times of each instruction are here at first hand.
- K. R. Irvine, Assembly Language for x86 Processors (7th ed.), Chapter 7: integer arithmetic, multiword shifts and addition, ASCII and packed decimal arithmetic.
- emu8086 documentation, "8086 instructions": a short description of each instruction, its flag table and example code; it is the source of the BCD examples in the slides.
6.18References
- Intel, The 8086 Family User's Manual, 1979 — Instruction Set section.
- B. B. Brey, The Intel Microprocessors, 8th ed., Pearson, 2009 — Chapter 5.
- emu8086 help documents: "8086 instructions" and "Arithmetic and logic instructions".
- K. R. Irvine, Assembly Language for x86 Processors, 7th ed., Pearson, 2014 — Chapter 7.
- A. S. Tanenbaum, Modern Operating Systems, 3rd ed., Pearson, 2008.
- M. Bodur, Mikroişlemcilere Giriş: Assembler ile Yazılım ve Arayüz (in Turkish), EMO, 2014.
- Ş. Ç. Öztürk, O. Ergin, Intel 8086 ile Mikroişlemci Programlamaya Giriş (in Turkish), 2009.