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.

1514131211OF10DF9IF8TF7SF6ZF54AF32PF10CFcontrol flags: DF, IF, TFstatus flags: OF, SF, ZF, AF, PF, CF
Figure 6.1: The 16-bit flags register. The dashed bits are not used on the 8086; the six status flags (CF, PF, AF, ZF, SF, OF) hold the result of arithmetic and logic instructions.

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.

Table 6.1: The flags of the 8086. Status flags describe the result; control flags govern the behavior of the processor.
BitFlagTypeSet to 1 if…Example
0CF (carry)statusunsigned overflow: a carry out of the most significant bit in addition, a borrow in subtractionFFh + 01h → AL = 00h, CF = 1; 7 − 9 → CF = 1
2PF (parity)statusthe low byte of the result has an even number of 1 bits96h = 1001 0110b → four 1s → PF = 1
4AF (auxiliary carry)statusa carry or borrow from bit 3 to bit 408h + 08h = 10h → AF = 1
6ZF (zero)statusall bits of the result are 0SUB AL, AL → ZF = 1
7SF (sign)statusthe most significant bit (MSB) of the result is 196h → SF = 1
8TF (trap)controlINT 1 after every instruction (single step)used by debuggers
9IF (interrupt)controlinterrupts from the INTR pin are acceptedSTI → 1, CLI → 0
10DF (direction)controlstring instructions decrement SI and DICLD → 0, STD → 1
11OF (overflow)statussigned overflow: the result did not fit in the signed range100 + 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.

Definition 6.1

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.

Table 6.2: The unsigned and signed readings of the same byte addition. CF says the unsigned result is wrong, OF the signed one.
AL + operandUnsigned readingSigned readingALCFOF
FFh + 01h255 + 1 = 256−1 + 1 = 000h10
64h + 32h100 + 50 = 150100 + 50 = 15096h01
C8h + 64h200 + 100 = 300−56 + 100 = 442Ch10
80h + 80h128 + 128 = 256−128 + (−128) = −25600h11
05h + 0Ah5 + 10 = 155 + 10 = 150Fh00

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.

Rule (overflow flag)

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.

Common mistake

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
Table 6.3: Trace of CF, OF and the other flags. Each row is the state after the instruction executes; at the start all status flags are 0.
InstructionMachine codeALCFOFSFZFAFPF
MOV AL, 9ChB0 9C9Ch000000
ADD AL, 70h04 700Ch100001
MOV AL, 50hB0 5050h100001
ADD AL, 50h04 50A0h011001
ADD AL, AL02 C040h110000
MOV AL, 0FFhB0 FFFFh110000
INC ALFE C000h100111
CMCF500h000111

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.

A = 64h0716150403120100B = 32h00110010AL = 96h10010110four 1s (even) → PF = 14 + 2 nibble: no carry → AF = 0
Figure 6.2: 64h + 32h = 96h. The bits are added from right to left; the flags are read from the bits of the result and from the carries.
  1. Result. 0110 0100b + 0011 0010b = 1001 0110b = 96h. In the unsigned reading 150 is correct; in the signed reading −106 is wrong.
  2. CF. No carry came out of the leftmost bit; 150 ≤ 255. CF = 0.
  3. OF. The carry into bit 7 is 1, the carry out is 0. The sum of two positive numbers looked negative. OF = 1.
  4. SF and ZF. Bit 7 of the result is 1, SF = 1. The result is not zero, ZF = 0.
  5. PF. 1001 0110b has four 1s; four is even, PF = 1.
  6. 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.

Example 6.1

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.

destination ← destination ∘ sourceADD AX, BXAX ← AL × operandMUL BLoperand ← f(operand)INC CX
Figure 6.3: The operand forms of the three groups. In group 1 the result is written to the destination; in group 2 the implicit AL, AX and DX are used; in group 3 the single operand is both source and destination.
  • 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 CX reads 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.

Table 6.4: The meaning of the instructions in the three groups.
GroupInstructionWhat it does
1ADDadds two values, writes the result to the destination
SUBsubtracts the source from the destination, writes the result to the destination
CMPsubtracts the source from the destination, does not store the result; only sets the flags
ANDbitwise AND
TESTbitwise AND; does not store the result
ORbitwise OR
XORbitwise exclusive OR
2MULunsigned multiplication
IMULsigned multiplication
DIVunsigned division (quotient and remainder)
IDIVsigned division (quotient and remainder)
3INCincrements by 1
DECdecrements by 1
NOTinverts all bits (ones' complement)
NEGnegates (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).

Table 6.5: The valid operand combinations of ADD, SUB, CMP, AND, TEST, OR and XOR.
FormExampleMachine code
REG, memoryADD AX, [BX]03 07
memory, REGSUB var1, CL28 0E + address
REG, REGXOR AX, AX33 C0
memory, immediateAND BYTE PTR [SI], 0Fh80 24 0F
REG, immediateCMP 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.

Common mistake

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.

Table 6.6: The flag effect of the two-operand instructions. ✓ set according to the result, 0 always cleared, ? undefined.
InstructionCFZFSFOFPFAF
ADD, ADC, SUB, SBB, CMP✓✓✓✓✓✓
AND, OR, XOR, TEST0✓✓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).

Table 6.7: Clock cycle counts of the two-operand instructions on the 8086 (Intel manual). For a word access at an odd address, 4 cycles are added for each transfer.
FormADD, ADC, SUB, SBB, AND, OR, XORCMPTEST
reg, reg333
reg, mem9 + EA9 + EA9 + EA
mem, reg16 + EA9 + EA9 + EA
reg, imm445
mem, imm17 + EA10 + EA11 + EA
AL/AX, imm444

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
Table 6.8: Trace of ADD, SUB and CMP (all status flags 0 at the start).
InstructionMachine codeALBLCFZFSFOFPFAF
mov al, 0F0hB0 F0F0h00h000000
add al, 20h04 2010h00h100000
mov bl, 7B3 0710h07h100000
sub bl, 980 EB 0910hFEh101001
cmp al, 10h3C 1010hFEh010010
cmp bl, 080 FB 0010hFEh001000
add bl, 280 C3 0210h00h110011

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.

Table 6.9: Three CMP examples. The unsigned result is read from CF, the signed result from the comparison of SF and OF.
InstructionsCFSFOFUnsignedSigned
AL = 05h, BL = FEh; CMP AL, BL1005 < 2545 > −2 (SF = OF)
AL = 7Fh, BL = 80h; CMP AL, BL111127 < 128127 > −128 (SF = OF)
AL = 80h, BL = 01h; CMP AL, BL001128 > 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.

Definition 6.2

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
Table 6.10: Trace of the addition 0001FFFFh + 00020001h.
InstructionMachine codeDXAXCXBXCFZF
mov ax, 0FFFFhB8 FF FF0000hFFFFh0000h0000h00
mov dx, 0001hBA 01 000001hFFFFh0000h0000h00
mov bx, 0001h · mov cx, 0002hBB 01 00 · B9 02 000001hFFFFh0002h0001h00
add ax, bx03 C30001h0000h0002h0001h11
adc dx, cx13 D10004h0000h0002h0001h00

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
Table 6.11: Trace of the subtraction 00040000h − 00010001h.
InstructionMachine codeDXAXCX:BXCFSF
mov ax, 0000h · mov dx, 0004hB8 00 00 · BA 04 000004h0000h0000:0000h00
mov bx, 0001h · mov cx, 0001hBB 01 00 · B9 01 000004h0000h0001:0001h00
sub ax, bx2B C30004hFFFFh0001:0001h11
sbb dx, cx1B D10002hFFFFh0001:0001h00

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.

Example 6.2

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).

Common mistake

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.

Table 6.12: Truth tables of AND, OR, XOR and NOT.
ABA AND BA OR BA XOR BNOT A
000001
010111
100110
111100

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.

AL='a' 61h0716150403020110mask DFh11011111ANDAL='A' 41h01000001AL='A' 41h0716050403020110mask 20h00100000ORAL='a' 61h01100001AL='a' 61h0716150403020110mask 20h00100000XORAL='A' 41h01000001BL='7' 37h0706151403121110mask 01h00000001TEST(not stored)00000001
Figure 6.4: Masking. AND DFh clears bit 5 ('a' → 'A'); OR 20h sets bit 5 ('A' → 'a'); XOR 20h inverts bit 5; TEST 01h tests bit 0 and does not change BL.

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.

Table 6.13: Frequently used patterns with logic instructions.
CodeEffectWhy?
XOR AX, AXAX = 0, ZF = 1, CF = 02 bytes (33 C0); MOV AX, 0 is 3 bytes (B8 00 00) and does not touch the flags
AND AL, 0Fh'7' (37h) → 7converts an ASCII digit to a number; the high nibble is cleared
OR AL, 30h7 → '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, 1odd if ZF = 0bit 0 is tested without changing AL
TEST AL, 80hnegative if ZF = 0the sign bit is tested
OR AX, AXAX unchangedZF 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
Table 6.14: Trace of the logic instructions. After logic instructions CF = OF = 0; AF is undefined (not shown in the table).
InstructionMachine codeALBLZFSFPFCFOF
mov al, 'a'B0 6161h00h00000
and al, 0DFh24 DF41h 'A'00h00100
or al, 20h0C 2061h 'a'00h00000
xor al, 20h34 2041h 'A'00h00100
mov bl, '7'B3 3741h37h00100
and bl, 0Fh80 E3 0F41h07h00000
test bl, 1F6 C3 0141h07h00000
xor bl, bl32 DB41h00h10100

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.

Common mistake

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.

byte operand (8 bit)AL×operandAX (16 bit)MUL / IMULword operand (16 bit)AX×operandDXAX32-bit result DX:AX (DX high)
Figure 6.5: In byte multiplication AL × operand is written to AX, in word multiplication AX × operand to DX:AX.
Definition 6.3

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.

Table 6.15: Byte multiplication examples and CF/OF.
AL, BLInstructionCalculationAXCF = OFWhy
C8h, 03hMUL BL200 × 3 = 6000258h1AH = 02h ≠ 0
C8h, 03hIMUL BL−56 × 3 = −168FF58h1−168 does not fit a signed byte
FEh, 05hIMUL BL−2 × 5 = −10FFF6h0AH = FFh, the sign extension of AL
FEh, 05hMUL BL254 × 5 = 127004F6h1AH = 04h ≠ 0
06h, 09hMUL BL6 × 9 = 540036h0AH = 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.

DXAXdividend (32 bit)÷operanddivisor (16 bit)AXquotientDXremainderin byte division:AX ÷ operand → AL, AH
Figure 6.6: In word division DX:AX is the dividend and the operand is the divisor; the quotient goes to AX and the remainder to DX.
Table 6.16: The implicit operands of DIV and IDIV.
InstructionIf the operand is a byteIf the operand is a word
DIV (unsigned)AL ← AX / operand, AH ← remainderAX ← DX:AX / operand, DX ← remainder
IDIV (signed)AL ← AX / operand, AH ← remainderAX ← 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.

Definition 6.4

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.

Table 6.17: Byte and word multiplication and division examples.
StartInstructionResultExplanation
AL = C8h, BL = 03hMUL BLAX = 0258h, CF = OF = 1200 × 3 = 600; did not fit in AL
AL = C8h, BL = 03hIMUL BLAX = FF58h, CF = OF = 1−56 × 3 = −168; does not fit a signed byte
AL = FEh, BL = 05hIMUL BLAX = FFF6h, CF = OF = 0−2 × 5 = −10; AH is only the sign extension
AX = 0017h, BL = 05hDIV BLAL = 04h, AH = 03h (AX = 0304h)23 = 4 × 5 + 3
AX = FFE9h, BL = 05hIDIV BLAL = FCh, AH = FDh (AX = FDFCh)−23 = (−4) × 5 + (−3)
AX = 1000h, BL = 02hDIV BLINT 0the quotient 2048 does not fit in AL
DX:AX = FFFFFFFFh, BX = 0001hDIV BXINT 0the 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, 0 or XOR 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.
Definition 6.5

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.

AL11111001F9h = -7CBW: bit 7 is copied into AHAX1111111111111001FFF9h = -7
Figure 6.7: CBW: AL = F9h (−7); because the sign bit is 1, AH = FFh; AX = FFF9h is again −7.

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 = -6

In 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.

Common mistake

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
Table 6.18: Trace of DIV, CWD and IDIV. The flags are undefined after a division.
InstructionMachine codeDXAXBXDX:AX (decimal)
MOV AX, 2000B8 D0 070000h07D0h0000h2000
XOR DX, DX33 D20000h07D0h0000h2000
MOV BX, 9BB 09 000000h07D0h0009h2000
DIV BXF7 F30002h00DEh0009hquotient 222, remainder 2
MOV AX, -2000B8 30 F80002hF830h0009h0002F830h = 194,608 (wrong dividend)
CWD99FFFFhF830h0009hFFFFF830h = −2000
IDIV BXF7 FBFFFEhFF22h0009hquotient −222, remainder −2
MOV AX, 2000B8 D0 07FFFEh07D0h0009hFFFE07D0h ≈ 4.29 billion
DIV BXF7 F3divide 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
Table 6.19: Resolving signed overflow with JO and CBW.
InstructionAXDXCFOFSFExplanation
mov al, -92 · mov bl, -9200A4h0000h000−92 = 256 − 92 = 164 = A4h
add al, bl0048h0000h110A4h + A4h = 148h; AL = 48h = +72
jo widen0048h0000h110OF = 1: the jump is taken
mov al, -92 · cbwFFA4h0000h110the MSB of AL is 1 → AH = FFh
mov dx, ax · mov al, bl · cbwFFA4hFFA4h110both numbers are −92 as words
add ax, dxFF48hFFA4h101FFA4h + 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.

Definition 6.6

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
ret

The 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.

Table 6.20: The signed byte sum with CBW. The state after cbw and add bx, ax in each iteration.
IterationALAX after CBWBX (sum)CX (at the start of the iteration)Explanation
164h0064h0064h = 1004+100, MSB = 0 → AH = 00h
2E2hFFE2h0046h = 703−30, MSB = 1 → AH = FFh
35Ah005Ah00A0h = 1602+90
4F9hFFF9h0099h = 1531−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.

Common mistake

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
ret

The 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.

Table 6.21: Trace of the 32-bit total with CWD and ADC (after ADD and ADC in each iteration).
IterationAXCWD: DXTotal after ADD, CFtotal+2 after ADC32-bit total
17530h (30.000)0000h7530h, CF = 00000h00007530h = 30.000
261A8h (25.000)0000hD6D8h, CF = 00000h0000D6D8h = 55.000
3F060h (−4000)FFFFhC738h, CF = 10000h0000C738h = 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.

z3 · bits 48–63z2 · bits 32–47z1 · bits 16–31z0 · bits 0–15A =9ABC (A1)DEF0 (A0)× B =EDCB (B1)FEDC (B0)A0 × B01. MULDDF1B640A1 × B02nd MUL · shifted 16 bits9A0B8190A0 × B13rd MUL · shifted 16 bitsCF14F850A1 × B14th MUL · shifted 32 bits8FBABF14+2 carry+2 carrycolumn carriesA × B =8FBC283557D1B640
Figure 6.8: The product of A = 9ABCDEF0h and B = EDCBFEDCh. The four partial products are added by columns; the column carries pass to the next word up.

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
Table 6.22: Trace of the 32 × 32-bit multiplication. z3…z0 are the four words of the result (0 at the start).
Instruction(s)DX:AXCFz3z2z1z0
mov ax,[x] · mul [y]DDF1:B640h10000h0000h0000h0000h
mov [z],ax · mov [z+2],dxDDF1:B640h10000h0000hDDF1hB640h
mov ax,[x+2] · mul [y]9A0B:8190h10000h0000hDDF1hB640h
add [z+2],ax9A0B:8190h10000h0000h5F81hB640h
adc [z+4],dx9A0B:8190h00000h9A0Ch5F81hB640h
mov ax,[x] · mul [y+2]CF14:F850h10000h9A0Ch5F81hB640h
add [z+2],axCF14:F850h10000h9A0Ch57D1hB640h
adc [z+4],dxCF14:F850h10000h6921h57D1hB640h
adc [z+6],0CF14:F850h00001h6921h57D1hB640h
mov ax,[x+2] · mul [y+2]8FBA:BF14h10001h6921h57D1hB640h
add [z+4],ax8FBA:BF14h10001h2835h57D1hB640h
adc [z+6],dx8FBA:BF14h08FBCh2835h57D1hB640h

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.
Table 6.23: The flag effect of the single-operand instructions. ✓ set according to the result, — unchanged.
InstructionCFZFSFOFPFAF
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 = 05h0706050403120110NOT x11111010FAh+ 1 → NEG11111011FBhx = 80h1706050403020100NOT x011111117Fh+ 1 → NEG1000000080h
Figure 6.9: The two steps of NEG: first NOT (ones' complement), then +1. On the left 05h → FAh → FBh (−5); on the right 80h → 7Fh → 80h: the negative of −128 does not fit in a byte.
Table 6.24: NEG on four byte values.
xNOT xNEG xCFOFExplanation
05h (5)FAh (−6)FBh (−5)10the negative of a positive
FEh (−2)01h02h (2)10the negative of a negative is positive
80h (−128)7Fh80h11+128 does not fit in a byte
00hFFh00h00ZF = 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
Table 6.25: Trace of INC, DEC, NOT and NEG (all status flags 0 at the start).
InstructionMachine codeALBLCFZFSFOFPFAF
mov al, 0FFhB0 FFFFh00h000000
inc alFE C000h00h010011
dec alFE C8FFh00h001011
mov bl, 7FhB3 7FFFh7Fh001011
inc blFE C3FFh80h001101
not blF6 D3FFh7Fh001101
neg blF6 DBFFh81h101011

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.

b7b6b5b4b3b2b1b0CF0b7b6b5b4b3b2b1b0CF0b7b6b5b4b3b2b1b0CFthe sign bit is preserved
Figure 6.10: SHL/SAL (0 enters from the right, b7 goes to CF), SHR (0 enters from the left, b0 goes to CF) and SAR (the sign bit stays in place and copies itself, b0 goes to CF).
Definition 6.7

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.

b7b6b5b4b3b2b1b0CFb7b6b5b4b3b2b1b0CFb7b6b5b4b3b2b1b0CFb7b6b5b4b3b2b1b0CF
Figure 6.11: ROL and ROR rotate in an 8-bit ring and write a copy of the bit that leaves to CF. RCL and RCR include CF in the ring: a 9-bit ring for a byte, 17 bits for a word.
  • 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.
Table 6.26: The one-step result of seven instructions for AL = 96h (1001 0110b). For RCL and RCR the initial CF changes the result.
InstructionWith CF = 0With CF = 1Result CFOF
SHL AL, 12Ch (0010 1100)2Ch11
SHR AL, 14Bh (0100 1011)4Bh01
SAR AL, 1CBh (1100 1011)CBh00
ROL AL, 12Dh (0010 1101)2Dh11
ROR AL, 14Bh (0100 1011)4Bh01
RCL AL, 12Ch (0010 1100)2Dh (0010 1101)11
RCR AL, 14Bh (0100 1011)CBh (1100 1011)01 / 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 0

There 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.

Table 6.27: Computing 13 × 5 by shifting. Each row is one iteration: the bit shifted out by SHR, the addition, and the state after SHL.
IterationDL (after SHR)CFAdditionresultBL (after SHL)CX (after LOOP)
102h10 + 0Dh0Dh (13)1Ah (26)3
201h0skipped0Dh34h (52)2
300h10Dh + 34h41h (65)68h (104)1
400h0skipped41hD0h0

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 → −2

For 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
Table 6.28: Trace of 37 × 10 and 370 ÷ 16.
InstructionMachine codeAXAX (binary)BXCL
mov ax, 37B8 25 000025h = 370000 0000 0010 01010000h00h
shl ax, 1D1 E0004Ah = 740000 0000 0100 10100000h00h
mov bx, ax8B D8004Ah0000 0000 0100 1010004Ah = 7400h
shl ax, 1D1 E00094h = 1480000 0000 1001 0100004Ah00h
shl ax, 1D1 E00128h = 2960000 0001 0010 1000004Ah00h
add ax, bx03 C30172h = 3700000 0001 0111 0010004Ah00h
mov bx, ax8B D80172h0000 0001 0111 00100172h00h
and bx, 000Fh83 E3 0F0172h0000 0001 0111 00100002h00h
mov cl, 4B1 040172h0000 0001 0111 00100002h04h
shr ax, clD3 E80017h = 230000 0000 0001 01110002h04h

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
ret

The structure of the program, line by line, is as follows.

  • JMP start jumps 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, and MOV [DI], AL writes 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 sum builds 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

Table 6.29: Trace of the array summation program.
StepSIBXDICXALvec3Explanation
jmp start0000h0000h0000h0000h00h0 0 0 0the data (0102h–010Dh) is skipped
lea si / bx / di0102h0106h010Ah0000h00h0 0 0 0the addresses of the three arrays
mov cx, 40102h0106h010Ah0004h00h0 0 0 04 iterations
iteration 1: mov al,[si] · add al,[bx]0102h0106h010Ah0004h04h0 0 0 01 + 3 = 4
iteration 1: mov [di],al0102h0106h010Ah0004h04h4 0 0 0vec3[0] = 4
iteration 1: three inc · loop0103h0107h010Bh0003h04h4 0 0 0CX = 3 ≠ 0 → back to sum
iteration 20104h0108h010Ch0002h07h4 7 0 02 + 5 = 7
iteration 30105h0109h010Dh0001h0Bh4 7 11 05 + 6 = 11
iteration 40106h010Ah010Eh0000h07h4 7 11 76 + 1 = 7; CX = 0, the loop ends
vec1 (0102h)1256vec2 (0106h)3561▲SIvec3 (010Ah)47117▲BX
Figure 6.12: Memory when the program ends: vec3 = 4, 7, 11, 7 (04h 07h 0Bh 07h). After the last iteration SI points to the start of vec2 and BX to the start of vec3.

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.

Table 6.30: The bytes of the array summation program in memory (emu8086).
AddressBytesMeaning
0100hEB 0CJMP 010Eh; target = 0102h + 0Ch
0102h01 02 05 06vec1 (data)
0106h03 05 06 01vec2 (data)
010Ah04 07 0B 07vec3 (after the program has run)
010EhBE 02 01MOV SI, 0102h (the code of LEA)
0111hBB 06 01MOV BX, 0106h
0114hBF 0A 01MOV DI, 010Ah
0117hB9 04 00MOV CX, 0004h; the constant is little-endian
011Ah8A 04MOV AL, [SI] (sum:)
011Ch02 07ADD AL, [BX]
011Eh88 05MOV [DI], AL
0120h46 43 47INC SI, INC BX, INC DI (one byte each)
0123hE2 F5LOOP 011Ah; F5h = −11
0125hC3RET

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.

Definition 6.8

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.

Table 6.31: Four representations of the number 14.
RepresentationBitsByte(s)
Binary0000 11100Eh
Unpacked BCD0000 0001 · 0000 010001h 04h (AH, AL)
Packed BCD0001 010014h
ASCII0011 0001 · 0011 010031h 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

Table 6.32: The BCD adjust instructions. All are one-byte instructions with implicit operands (AAM and AAD are two bytes).
InstructionWhenEffectTime (cycles)
AAAafter unpacked additionadjusts AL to BCD, carry into AH4
AASafter unpacked subtractionadjusts AL, borrow from AH4
AAMafter unpacked multiplicationAH ← AL / 10, AL ← AL mod 1083
AADbefore unpacked divisionAL ← AH × 10 + AL, AH ← 060
DAAafter packed additionadjusts the two digits in AL4
DASafter packed subtractionadjusts the two digits in AL4

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.

Rule (AAA and DAA)

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
Table 6.33: Trace of 9 + 5 with AAA. "14" appears on the screen.
InstructionMachine codeAXBLCFAFExplanation
mov ah, 09h · mov al, 05hB4 09 · B0 050905h00h00two digits
add al, ah02 C4090Eh00h009 + 5 = 0Eh; right in binary, not BCD
xor ah, ah32 E4000Eh00h0?the tens digit is cleared
aaa370104h00h11E > 9: AL + 6 = 14h, AH + 1, the high nibble is cleared
or ax, 3030h0D 30 303134h00h0?'1', '4'
mov bl, al · mov al, ah8A D8 · 8A C43131h34h0?'4' saved, AL = '1'
mov ah, 0Eh · int 10hB4 0E · CD 100E31h34h0?'1' on the screen
mov al, bl · int 10h8A C3 · CD 100E34h34h0?'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
Table 6.34: Trace of 5 − 8 with AAS. The program starts with AX = 0000h.
InstructionAXBLCFAFSFExplanation
mov al, 05h · mov bl, 08h0005h08h000
sub al, bl00FDh08h1115 − 8 = −3 = FDh
aasFF07h08h11?AL − 6 = F7h, AH − 1 = FFh; the high nibble is cleared
or al, 30hFF37h08h0?0AL = '7'
mov ah, 0Eh · int 10h0E37h08h0?0'7' on the screen
mov ah, 0 · int 16h—08h0?0waits 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.

Definition 6.9

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 = 00h

In 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
Table 6.35: Trace of AAM, AAD and DAA. ? is an undefined flag.
InstructionMachine codeAXBLAFCFExplanation
MOV AL, 6 · MOV BL, 9B0 06 · B3 090006h09h00
MUL BLF6 E30036h09h?06 × 9 = 54; fits in AL
AAMD4 0A0504h09h??unpacked "54"
MOV AX, 0702hB8 02 070702h09h??unpacked "72"
AADD5 0A0048h09h??7 × 10 + 2 = 72 = 48h
MOV BL, 8 · DIV BLB3 08 · F6 F30009h08h??72 / 8 = 9, remainder 0
MOV AL, 19hB0 190019h08h??packed "19"
ADD AL, 28h04 280041h08h109 + 8 = 17: carry out of the nibble
DAA270047h08h10AF = 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.

Common mistake

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
Table 6.36: Converting 15 °C to Fahrenheit.
InstructionMachine codeAXCLCFOFExplanation
mov cl, 15B1 0F0000h0Fh00c = 15
mov al, 9B0 090009h0Fh00
imul clF6 E90087h0Fh119 × 15 = 135; does not fit a signed byte, but is complete in AX
mov cl, 5B1 050087h05h11divisor
idiv clF6 F9001Bh05h??135 / 5 = 27, remainder 0
add al, 3204 20003Bh05h0027 + 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
Table 6.37: Converting 59 °F to Celsius.
InstructionMachine codeAXCLCFOFExplanation
mov cl, 59B1 3B0000h3Bh00f = 59
sub cl, 3280 E9 200000h1Bh0059 − 32 = 27
mov al, 5B0 050005h1Bh00
imul clF6 E90087h1Bh115 × 27 = 135
mov cl, 9 · idiv clB1 09 · F6 F9000Fh09h??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.

Table 6.38: The limit values of the °C → °F program.
cIMUL: AXIDIV: ALAL after ADDOFResult
−72FD78h (−648)quotient −129 does not fit → INT 0divide error
−71FD81h (−639)81h (−127)A1h (−95)0correct
−10FFA6h (−90)EEh (−18)0Eh (14)0correct
5301DDh (477)5Fh (95)7Fh (127)0correct (the largest)
5401E6h (486)61h (97)81h1wrong: read as −127
720288h (648)quotient 129 does not fit → INT 0divide 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.

Table 6.39: The effect of the instructions on the status flags. ✓ according to the result, 0 cleared, — unchanged, ? undefined, ¹ defined only when the count is 1.
InstructionCFZFSFOFPFAF
ADD SUB CMP ADC SBB✓✓✓✓✓✓
NEG✓✓✓✓✓✓
INC DEC—✓✓✓✓✓
AND OR XOR TEST0✓✓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

Table 6.40: Common mistakes with arithmetic and logic instructions.
MistakeWhat happens?Correct
Looking at CF with signed numberscorrect results such as −1 + 1 are taken as "overflowed"signed: OF; in comparisons SF ≠ OF
Forgetting DX before DIV BXthe old DX enlarges the dividend; wrong result or INT 0XOR DX, DX or CWD
MOV AH, 0 for a signed byte−30 = E2h is counted as 226CBW
MUL 10the 8086 has no immediate operand; the assembler rejects itMOV BL, 10 · MUL BL
SHL AX, 4an 80186 instruction; does not work on the 8086MOV CL, 4 · SHL AX, CL
ADD on both wordsthe carry of the low word is lostADD, then ADC
A CMP between ADD and ADCCF is erasedonly MOV, INC, DEC, LOOP in between
AND to test a bitthe other bits of the number are erasedTEST
Dividing a negative number with SAR and expecting the IDIV result−7 / 2: SAR −4, IDIV −3choosing the rounding direction knowingly
Writing AAD after DIVthe unpacked number is taken for binary: 0702h = 1794 is dividedAAD before the division
Common mistake

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 sum

With 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 again

For 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

  1. What are AL and the six status flags after MOV AL, 9Ch and ADD 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.

  2. What CF and OF values does SUB AL, BL give 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.

  3. With AL = F0h, BL = 10h, what are AX and CF after IMUL BL and after MUL 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.

  4. 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.

  5. With CF = 1 and AL = 81h, what are AL and CF after three consecutive RCL AL, 1 instructions?

    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.

  6. 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.

  7. 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.

  8. 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. If INC AX had been used, CF would not have changed and the carry would have been lost.

  9. What are AX, CF and OF after MOV AX, 8000h and NEG 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.

  10. What is the difference between INC AX and ADD AX, 1 in machine code, time and flags?

    Answer

    INC AX is a single byte (40) and takes 2 clock cycles; it does not touch CF. ADD AX, 1 is 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

  1. Intel, The 8086 Family User's Manual, 1979 — Instruction Set section.
  2. B. B. Brey, The Intel Microprocessors, 8th ed., Pearson, 2009 — Chapter 5.
  3. emu8086 help documents: "8086 instructions" and "Arithmetic and logic instructions".
  4. K. R. Irvine, Assembly Language for x86 Processors, 7th ed., Pearson, 2014 — Chapter 7.
  5. A. S. Tanenbaum, Modern Operating Systems, 3rd ed., Pearson, 2008.
  6. M. Bodur, Mikroişlemcilere Giriş: Assembler ile Yazılım ve Arayüz (in Turkish), EMO, 2014.
  7. Ş. Ç. Öztürk, O. Ergin, Intel 8086 ile Mikroişlemci Programlamaya Giriş (in Turkish), 2009.