The Complexity of Division
While multiplication (Part 16) is complex, floating-point division is arguably the most difficult operation to implement in Z80 assembly. It combines the complexity of multi-byte arithmetic with the iterative processes of long division, applied across three components: Sign, Exponent, and Mantissa.
The Formula (Conceptual): $$\text{Result}_{\text{Sign}} = \text{Operand}_A.\text{Sign} \text{ XOR } \text{Operand}B.\text{Sign}$$ $$\text{Result}{\text{Exponent}} = \text{Operand}_A.\text{Exponent} - \text{Operand}B.\text{Exponent}$$ $$\text{Result}{\text{Mantissa}} = \text{Operand}_A.\text{Mantissa} / \text{Operand}_B.\text{Mantissa}$$
Step 1: Sign and Exponent Calculation
The sign of the result is determined by a simple XOR
operation on the two input sign bits (Part 8).
The new exponent is a straightforward subtraction of the two input exponents (which are usually stored with a fixed offset, or bias, added to them).
Exponent Subtraction (Z80):
LD A, A_EXPONENT ; A ← Exponent of Operand A
SBC A, B_EXPONENT ; A ← A - B_EXPONENT (SBC is used to handle borrow)
LD RESULT_EXPONENT, A ; Store the new exponent
Step 2: Mantissa Division (The Core Algorithm)
The mantissa division is performed on the two large integer parts of the numbers. Since the Z80 has no division instruction, this is done using repeated subtraction or repeated shifting and subtraction (the standard long division algorithm).
Iterative Division Logic:
- The process loops 24 times (for a 24-bit mantissa).
- In each loop, the Divisor (Mantissa B) is repeatedly subtracted from the Dividend (Mantissa A).
- A result bit of ‘1’ is generated if subtraction is successful; otherwise, a ‘0’ is generated.
- The Remainder is then shifted and processed in the next loop.
Z80 Implementation Focus: This routine heavily relies on the `SBC HL, DE′ instruction (Subtract 16-bit register DE from HL with Carry) for multi-word subtraction, checking the Carry Flag (C) after each operation to determine if the division step was successful.
Step 3: Normalization and Rounding
After the division produces the raw result, the floating-point number must be normalized (adjusting the exponent and mantissa to fit the standard form) and often rounded to fit the 24-bit mantissa field.
Rounding Method: Typically, the routine checks the value of the bit immediately after the mantissa’s last bit to decide whether to round up (add ‘1’ to the mantissa) or truncate (discard the rest).
Final Output: The complex routine terminates by assembling the three final parts (Sign, Exponent, Mantissa) into the final 32-bit floating-point number at the designated memory location.