← r0mheat z80 lessons: all projects

Z80 assembly: BCD numbers and DAA

Add packed decimal digits. Use DAA to adjust the binary result into BCD form.

DAA

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.

Run speed

What happened

Program listing

AddressMachine codeLabelInstructionComment

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

#AddressInstructionResultT-states

BCD and binary values differ

BitsAs binaryAs packed BCD
45h69 decimal45 decimal
38h56 decimal38 decimal
7Dh125 decimalInvalid BCD digits
83h131 decimal83 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
NameStands forMeaning here
LDLoadLoads the first packed BCD number into A.
ADDAddAdds packed BCD values as binary.
SUBSubtractSubtracts packed BCD values as binary.
DAADecimal Adjust AccumulatorAdjusts the result to packed BCD.
HALTHaltStops after both examples.
ORGOriginAssembler directive. Sets the code address.