The Challenge of Floating-Point
The Z80 is an integer processor—it can only handle whole numbers. Floating-point numbers (like 3.14159 or 1.2e-5) are necessary for high-precision math used in physics simulations, graphics transformations, or advanced financial calculations. To use them, we must emulate the standard IEEE 754 format using multiple bytes of memory.
Floating-Point Structure (The Four-Byte Standard):
A typical 32-bit (4-byte) single-precision float is stored across four consecutive memory locations:
Byte Position | Bits | Value Stored |
---|---|---|
Byte 3 (Highest Address) | 1 | Sign (0=Positive, 1=Negative) |
Byte 3 | 8 | Exponent (Controls magnitude, e.g., 10**N) |
Byte 2-0 (Lowest Address) | 23 | Mantissa / Fraction (Controls precision) |
Emulation Libraries
Writing floating-point routines (addition, subtraction, multiplication, division) in assembly from scratch is extremely complex. This task is almost always handled by an existing Floating-Point Library written for the Z80.
How Libraries Work:
- The library contains hundreds of complex subroutines (like
FP_ADD
orFP_MULTIPLY
). - You pass the memory addresses of the two floating-point numbers you want to operate on (often in the
HL
andDE
register pairs). - You
CALL
the library routine. - The routine performs the multi-byte operation and leaves the 4-byte result at a designated memory location.
Example: Calling an FP Addition Routine
; Assume 32-bit floats A and B are stored in memory.
LD HL, ADDR_OF_FLOAT_A ; HL points to Operand A
LD DE, ADDR_OF_FLOAT_B ; DE points to Operand B
CALL FP_ADD_ROUTINE ; Call the library function
; Result is now located at ADDR_OF_FLOAT_A (or a scratchpad area)
The Performance Trade-off
Floating-point emulation is significantly slower than integer arithmetic because every single operation involves multiple loads, shifts, and conditional jumps across four bytes.
Best Practice: Use floating-point only when absolutely necessary. If you can perform the calculation using scaled integers (e.g., representing $1.5$ as $150$), integer math will be orders of magnitude faster.