DAA

From GbdevWiki
Revision as of 08:46, 25 May 2012 by Beannaich (Talk | contribs)

Jump to: navigation, search

If an addition operation is performed between 15 (BCD) and 27 (BCD), simple decimal arithmetic gives this result:

  15
+ 27
  --
  42

But when the binary representations are added in the Accumulator according to standard binary arithmetic.

  0001 0101
+ 0010 0111
  ---------
  0011 1100 = $3C

the sum is ambiguous. The DAA instruction adjusts this result so that the correct BCD representation is obtained:

  0011 1100
+ 0000 0110
  0100 0010 = $42

Instructions

DAA - $27 - 1 Machine Cycle

Flags

Z: 1 if Accumulator is zero after operation; 0 otherwise
N: not affected
H: 0
C: 1 if N is 0 and A is greater than $99, 0 otherwise

Pseudo-code

void DAA(void)
{
    if (n)
    {
        if (c) { reg.a -= 0x60; }
        if (h) { reg.a -= 0x06; }
    }
    else
    {
        if (c || (reg.a & 0xFF) > 0x99) { reg.a += 0x60; c = 1; }
        if (h || (reg.a & 0x0F) > 0x09) { reg.a += 0x06; }
    }

    z = reg.a == 0;
    h = 0;
}