Z80 assembly: BCD numbers and DAA
Add packed decimal digits. Use DAA to adjust the binary result into BCD form.
BCD means Binary-Coded Decimal. Each decimal digit uses four bits. For example, 45 decimal is 45h in packed BCD. Normal binary addition can make invalid BCD digits. DAA means Decimal Adjust Accumulator. It adjusts A after an ADD or SUB operation.
DAA takes 4 T-states. It uses the N, H and C flags from the previous arithmetic instruction. It then updates S, Z, H, P/V and C. N keeps its previous value.
What happened
Program listing
| Address | Machine code | Label | Instruction | Comment |
|---|
The first calculation adds packed BCD 45h and 38h. The second subtracts 38h from 45h. Step through each arithmetic instruction and DAA.
Registers and flags
Flags
DAA reads H, N and C from the previous operation. It adjusts the low digit by 6 when needed and the high digit by 60h when needed. This page ignores undocumented X and Y bits.
Program bytes
Execution trace
| # | Address | Instruction | Result | T-states |
|---|
BCD and binary values differ
| Bits | As binary | As packed BCD |
|---|---|---|
| 45h | 69 decimal | 45 decimal |
| 38h | 56 decimal | 38 decimal |
| 7Dh | 125 decimal | Invalid BCD digits |
| 83h | 131 decimal | 83 decimal |
45h + 38h first produces binary 7Dh. DAA adjusts it to 83h, the packed BCD form of decimal 83.
DAA is used after an 8-bit ADD or SUB operation on packed BCD values. The program does not validate that the input digits are valid BCD.
Mnemonic glossary
Program mnemonics and directives
| Name | Stands for | Meaning here |
|---|---|---|
| LD | Load | Loads the first packed BCD number into A. |
| ADD | Add | Adds packed BCD values as binary. |
| SUB | Subtract | Subtracts packed BCD values as binary. |
| DAA | Decimal Adjust Accumulator | Adjusts the result to packed BCD. |
| HALT | Halt | Stops after both examples. |
| ORG | Origin | Assembler directive. Sets the code address. |