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.
What happened
Program listing
| Address | Machine code | Label | Instruction | Comment |
|---|
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
| # | Address | Instruction | Result | T-states |
|---|
Two ways to print a number
| Method | Work | Trade-off |
|---|---|---|
| Repeated subtraction | Count tens, then convert remainder | Small code; time depends on value |
| Lookup table | Read prebuilt character pairs | Faster; 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
| Name | Stands for | Meaning here |
|---|---|---|
| CP | Compare | Compares A with 10 without storing a result. |
| JR C | Jump Relative if Carry | Leaves the loop when A is below 10. |
| SUB | Subtract | Removes one group of ten. |
| OUT | Output | Sends each ASCII digit to port 00h. |
| HALT | Halt | Stops after both characters are sent. |