Z80 assembly: Printing decimal numbers

Convert a byte to two decimal characters and send them to the console.

SUB · OUT

Computers store this value in binary. A screen needs character codes. This program repeatedly subtracts 10 to count the tens, then turns both digits into ASCII by adding 30h.

The example starts with 42 decimal (2Ah). The output is the two characters “42”. The console is a teaching device on port 00h.

Run speed

What happened

Program listing

AddressMachine codeLabelInstructionComment

B counts tens. A becomes the remainder, from 0 to 9. ASCII digits 0–9 occupy 30h–39h.

Registers and flags

Flags

The console view shows bytes written to port 00h as characters.

Console output

Execution trace

#AddressInstructionResultT-states

Two ways to print a number

MethodWorkTrade-off
Repeated subtractionCount tens, then convert remainderSmall code; time depends on value
Lookup tableRead prebuilt character pairsFaster; uses more memory

This short example handles values from 0 to 99. More digits need hundreds and thousands too.

The simulator maps OUT (00h),A to a simple character console. Real Z80 computers use hardware-specific output routines.

Mnemonic glossary

Program mnemonics
NameStands forMeaning here
CPCompareCompares A with 10 without storing a result.
JR CJump Relative if CarryLeaves the loop when A is below 10.
SUBSubtractRemoves one group of ten.
OUTOutputSends each ASCII digit to port 00h.
HALTHaltStops after both characters are sent.