The Challenge of Displaying Numbers

Once the Z80 has calculated a final value (e.g., a score of 4296 decimal), this number is stored as a 16-bit binary value (1000010000000000B). To display it on the screen, we need to convert it into a sequence of decimal digits (4′, 2′, 9′, 6′) that can be looked up in the font table.

Goal: Convert a 16-bit binary number into a 16-bit BCD value (four decimal digits).

The Conversion Algorithm: Repeated Division

The standard technique for displaying an integer in any computer is repeated division by 10.

The Principle:

  1. The remainder of the division ($N \div 10$) is the units digit.
  2. The quotient is then divided by 10 to get the tens digit.
  3. This repeats until the quotient is zero.

Z80 Implementation Focus

This routine requires a specialized, optimized 16-bit division by a constant (10).

The Steps (Simplified):

BINARY_VAL_ADDR EQU 8000H   ; Address of the 16-bit binary number

CONVERT_ROUTINE:
    LD   HL, (BINARY_VAL_ADDR) ; HL ← Binary value (e.g., 4296 decimal)
    LD   BC, 0000H           ; BC ← Will accumulate the final BCD result

    ; --- Loop 1 (Units Digit) ---
    CALL DIVIDE_BY_TEN_16BIT ; HL ← Quotient, A ← Remainder (Units Digit)
    CALL STORE_UNITS_DIGIT   ; Store A into the low nibble of the BCD result (C)

    ; --- Loop 2 (Tens Digit) ---
    ; Now HL holds the new quotient (429)
    CALL DIVIDE_BY_TEN_16BIT
    CALL STORE_TENS_DIGIT    ; Store A into the high nibble of C

    ; --- Loop 3 (Hundreds Digit) ---
    ; ... (Continues for hundreds and thousands digits)

    RET

The Division Subroutine

The core complexity lies in writing the fast and accurate 16-bit division by 10 routine. This is done through a series of conditional subtractions or by using a multiplication reciprocal (multiplying by $0.1$ and adjusting the exponent).

Output Format: Once the four digits are isolated, they are stored in the final 16-bit BCD format (or converted directly to the 4 bytes of ASCII for display).

Zero Suppression: For cleaner output (e.g., displaying ‘42’ instead of ‘0042’), the routine checks the thousands and hundreds digits and suppresses leading zeros by replacing them with the ASCII space character (`20H′).