The Challenge of Displaying Floats
In Z80 assembly, a floating-point number is stored internally across multiple bytes (e.g., 4 or 5 bytes) in a specialized format (Part 30). The screen, however, only displays ASCII characters. Converting the binary float into a series of characters (“3”, “.”, “1”, “4”) is one of the most complex tasks in 8-bit programming.
The Conversion Strategy
The process is too complex for a single routine and is typically broken down into four major steps:
Step 1: Extract Exponent and Sign The routine first reads the sign bit (positive/negative) and the exponent byte from the floating-point structure. This determines where the decimal point will ultimately be placed.
Step 2: Normalize the Mantissa The mantissa (the precision part) is converted into a large integer that represents all the digits of the number without the decimal point.
Step 3: Repeated Division by Ten The core of the conversion is repeated integer division of the normalized mantissa by 10 (decimal). The remainder of each division is the next decimal digit (0-9).
Example Division Logic:
; Assume HL holds the 16-bit integer to be displayed
DIV_BY_TEN_LOOP:
; 1. Perform 16-bit division by 10 (a complex subroutine)
CALL DIVIDE_BY_TEN
; 2. The remainder (e.g., in register A) is the next digit
LD (HL), A ; Store the remainder (digit) in the output buffer
; 3. Check if the quotient is zero; if not, repeat
; ... (Check quotient and JP if NZ)
Step 4: Formatting the Output
After division is complete, the stream of digits is converted to ASCII and formatted:
- ASCII Conversion: Add
30H
(the ASCII offset) to each digit (e.g., 5 becomes35H
, the character ‘5’). - Decimal Point Placement: The original exponent value determines where the decimal point character (
2EH
) must be inserted into the stream of digits. - Sign Output: An ASCII minus sign (
2DH
) is prefixed to the string if the original sign bit was negative.
Result: The conversion requires hundreds of Z80 instructions and is why most Z80 systems relied on pre-compiled BASIC ROMs to handle this conversion, as writing it in pure assembly is a massive undertaking.