Skip to content

Format a 16-bit Decimal Number on Spectrum

A binary score is good for adding points.

A binary score is good for adding points. People would rather read 12345 than its two storage bytes. This formatter turns any unsigned 16-bit value into five decimal characters, ready for a text routine to place or translate into tile numbers.

The existing Numeric Display routines print two or three digits with a character-printer contract. This version instead returns a counted five-byte ASCII span over the full unsigned 16-bit range; choose the smaller printer when its range and output ownership suit the game.

Spectrum shows the working result FF FF 36 35 35 33 35 00.
The completed native caller shows hexadecimal state bytes. The field order below explains the result; the full verification packet retains every call.

Include, initialise and call

Bind VALUE_LO, VALUE_HI, DIGIT0, DIGIT1, DIGIT2, DIGIT3, DIGIT4, WORK_LO, WORK_HI as 9 contiguous private bytes in that order. Include the helper once. Call decimal_format_init at the deliberate reset boundary: it clears all named bytes, including inputs. Set your starting values afterwards. Call decimal_format_step when this service is needed.

Bind all nine contiguous bytes, set the two value bytes and call step. Render the five output bytes afterwards. ASCII is a logical output contract: the C64 demo uses a prepared hex font and NES normally needs tile-number mapping, so these five bytes do not automatically become screen characters on either machine.

VALUE_LO/VALUE_HI contain an unsigned little-endian integer 0–65,535 and survive the call. Step writes exactly five ASCII bytes DIGIT0–DIGIT4 with leading zeroes, no terminator, and finishes with WORK_LO/WORK_HI zero. The work bytes belong to the helper, not to a second caller running concurrently.

Reusable initialisation and service

component.inc
; SPDX-License-Identifier: MIT
; Format a 16-bit Decimal Number. Bind these contiguous private bytes: VALUE_LO, VALUE_HI, DIGIT0, DIGIT1, DIGIT2, DIGIT3, DIGIT4, WORK_LO, WORK_HI.
; init clears the whole block; step uses current inputs. No I/O, waits or IRQ owner.
; AF/BC/DE/HL may change; IX/IY survive.
decimal_format_init:
    xor a
    ld (VALUE_LO),a
    ld (VALUE_HI),a
    ld (DIGIT0),a
    ld (DIGIT1),a
    ld (DIGIT2),a
    ld (DIGIT3),a
    ld (DIGIT4),a
    ld (WORK_LO),a
    ld (WORK_HI),a
    ret
decimal_format_step:
    ld hl,(VALUE_LO)
    ld de,10000
    ld b,48
format_0:
    or a
    sbc hl,de
    jr c,format_done_0
    inc b
    jr format_0
format_done_0:
    add hl,de
    ld a,b
    ld (DIGIT0),a
    ld de,1000
    ld b,48
format_1:
    or a
    sbc hl,de
    jr c,format_done_1
    inc b
    jr format_1
format_done_1:
    add hl,de
    ld a,b
    ld (DIGIT1),a
    ld de,100
    ld b,48
format_2:
    or a
    sbc hl,de
    jr c,format_done_2
    inc b
    jr format_2
format_done_2:
    add hl,de
    ld a,b
    ld (DIGIT2),a
    ld de,10
    ld b,48
format_3:
    or a
    sbc hl,de
    jr c,format_done_3
    inc b
    jr format_3
format_done_3:
    add hl,de
    ld a,b
    ld (DIGIT3),a
    ld de,1
    ld b,48
format_4:
    or a
    sbc hl,de
    jr c,format_done_4
    inc b
    jr format_4
format_done_4:
    add hl,de
    ld a,b
    ld (DIGIT4),a
    ld (WORK_LO),hl
    ret
component_end:

State and ownership

Two input bytes, five output characters and two scratch bytes. For example 65,535 produces ASCII bytes 36 35 35 33 35 in hexadecimal. Read DIGIT0–DIGIT4 as a counted five-byte span; there is no trailing zero to scan for.

On this Z80 the live remainder stays in HL; WORK_LO/WORK_HI only receive the final zero. They are retained in this example’s nine-byte binding, not required by the CPU arithmetic. A smaller target-specific variant can remove those two fields and their init/final stores, but that changes the binding and needs fresh records; it is not a measured seven-byte version here.

AF/BC/DE/HL may change; IX/IY survive. A direct CALL uses two return-address stack bytes.

This implementation has fixed symbol bindings and one mutation owner. Independent users need distinct state blocks and scoped/renamed bindings; including another copy with the same global labels is not sufficient. Sequential queries may reuse a scratch block only after the previous result has been consumed. Do not let an interrupt and the main loop mutate the same block without a separately designed ownership policy.

The standalone tape program starts at $8000, disables interrupts and owns bitmap/attribute RAM. It does not return to BASIC. The helper itself never disables interrupts or touches the display.

A small caller you can adapt

The standalone program includes the helper and a separate client. Its read-only table exercises 96 valid inputs, then this client initialises once and retains state between calls. Replace the supplied input changes with your own game values; the display and packet machinery are diagnostics rather than dependencies of the component.

Buildable caller, bindings and include order

demo.asm
    org $8000
CUSTOM equ 0
BROKEN equ 0
SCORE_CAP equ 65535
QUEUE_CAP equ 4
REPEAT_DELAY equ 4
REPEAT_RATE equ 2
    include "caller.inc"
    include "exercise.inc"
component_start:
    include "component.inc"
    include "cases.inc"
    include "../../physics/rectangle-overlap/display.inc"
code_end:
STATE:
VALUE_LO: defb 0
VALUE_HI: defb 0
DIGIT0: defb 0
DIGIT1: defb 0
DIGIT2: defb 0
DIGIT3: defb 0
DIGIT4: defb 0
WORK_LO: defb 0
WORK_HI: defb 0
input_ptr: defw 0
output_ptr: defw 0
cases_left: defb 0
ready: defb 0
preview: defs 8,0
OUTPUT: defs 1300,0
    end start

A separate client retaining state between calls

exercise.inc, excerpt
preview_rules:
    if CUSTOM
    ld a,0
    ld (VALUE_LO),a
    ld a,16
    ld (VALUE_HI),a
    if BROKEN
    ld a,0
    ld (VALUE_HI),a
    call checked_step
    else
    call checked_step
    endif
    call emit_state
    else
    ld a,255
    ld (VALUE_LO),a
    ld a,255
    ld (VALUE_HI),a
    if BROKEN
    ld a,0
    ld (VALUE_HI),a
    call checked_step
    else
    call checked_step
    endif
    call emit_state
    endif
    ret

The eight display fields follow VALUE_LO, VALUE_HI, DIGIT0, DIGIT1, DIGIT2, DIGIT3, DIGIT4, WORK_LO; the full packet also retains WORK_HI. Each field is a hexadecimal byte. The working row is FF FF 36 35 35 33 35 00. The output is a completed diagnostic state, not a recording of movement, input or sound hardware.

Make it your own

The custom caller formats 4,096 instead of 65,535, producing 04096. To hide leading zeroes, choose a presentation policy after formatting while keeping at least the final zero for a value of zero.

Maintained custom configuration or caller

custom.asm
    org $8000
CUSTOM equ 1
BROKEN equ 0
SCORE_CAP equ 999
QUEUE_CAP equ 2
REPEAT_DELAY equ 6
REPEAT_RATE equ 3
    include "caller.inc"
    include "exercise.inc"
component_start:
    include "component.inc"
    include "cases.inc"
    include "../../physics/rectangle-overlap/display.inc"
code_end:
STATE:
VALUE_LO: defb 0
VALUE_HI: defb 0
DIGIT0: defb 0
DIGIT1: defb 0
DIGIT2: defb 0
DIGIT3: defb 0
DIGIT4: defb 0
WORK_LO: defb 0
WORK_HI: defb 0
input_ptr: defw 0
output_ptr: defw 0
cases_left: defb 0
ready: defb 0
preview: defs 8,0
OUTPUT: defs 1300,0
    end start

The observed custom row is 00 10 30 34 30 39 36 00. The retained records qualify these named configurations; a new input domain or larger layout needs its own bounds and fresh execution checks.

Common mistake and repair

The wrong client clears VALUE_HI before formatting. The number 65,535 becomes 255, displayed as 00255. Copy both bytes from the score or counter; a correct formatter cannot recover a lost high byte.

Deliberately wrong client selection

wrong.asm
    org $8000
CUSTOM equ 0
BROKEN equ 1
SCORE_CAP equ 65535
QUEUE_CAP equ 4
REPEAT_DELAY equ 4
REPEAT_RATE equ 2
    include "caller.inc"
    include "exercise.inc"
component_start:
    include "component.inc"
    include "cases.inc"
    include "../../physics/rectangle-overlap/display.inc"
code_end:
STATE:
VALUE_LO: defb 0
VALUE_HI: defb 0
DIGIT0: defb 0
DIGIT1: defb 0
DIGIT2: defb 0
DIGIT3: defb 0
DIGIT4: defb 0
WORK_LO: defb 0
WORK_HI: defb 0
input_ptr: defw 0
output_ptr: defw 0
cases_left: defb 0
ready: defb 0
preview: defs 8,0
OUTPUT: defs 1300,0
    end start
Spectrum shows the deliberate fault result FF 00 30 30 32 35 35 00.
The wrong client completes and records FF 00 30 30 32 35 35 00. Compare its state with the working row and the explained failure.

The wrong branch is in the displayed client above, selected by BROKEN. repaired.asm selects the original client again. Its executable matches demo exactly; Spectrum tape filenames can differ while loaded CODE is identical. The bad caller is a labelled experiment, not an alternative recommended implementation.

Cost and verification

The measured helper occupies 126 code bytes plus 9 named state bytes in this layout. Return addresses, alignment, tables and display diagnostics are additional. The sizes cover init and step together, not the whole standalone program.

Five digit stages subtract 10,000, 1,000, 100, 10 and 1. Each stage needs at most nine successful subtractions, so 45 is a safe upper bound for successful subtractions, plus five terminating comparisons. There is no hardware division or screen write. Convert when the displayed value changes rather than every frame if that saves useful work.

Packed BCD can trade conversion work for more expensive score updates, and lookup tables trade ROM space for conversion speed. A divide-based implementation suits some CPUs better. Signs, decimal points and values beyond 65,535 need a different contract and output width.

Four native runs use Spectrum 48K with stock ROM tape loading and USR entry; Asm198x 0.0.72 and Emu198x 0.44.2. Every run checks 96 table results, dirty initialisation and every state in a separate sequential trace against an independent integer model. This is boundary/varied-input qualification, not exhaustive coverage of every byte combination. Source/tool/firmware hashes, native startup and completion, preserved-register sentinels, immutable loaded code, actual helper extent, capture bytes and pixels, and exact repair are checked. Deliberately changed observations must fail. Firmware is hashed, never distributed.

Related reusable technique · Maths for Games · The Craft.

Source and native evidence.