AAA: ASCII Adjust AL After Addition

For information about interpreting this page, see the help page.
Opcode and MnemonicEncoding16 bit Mode32 bit Mode64 bit ModeDescription
37
AAA
ZOValidValidInvalidASCII adjust AL after addition.

Encoding

EncodingOperand
ZONone

Description

The AAA instruction converts the result of an addition of two BCD digits to a valid 2-digit BCD number.

This instruction will not be useful unless it immediately follows an ADD (Add) instruction using the AL register and a single digit operand (either register or immediate). An example of such usage is below.

Traditionally, this instruction is "ASCII Adjust After Addition". This would lead one to believe that it works on ASCII digits (030h (0) through 039h (9)), however this would be incorrect. This instruction actually operates on BCD digits (00h (0) through 09h (9)).

This instruction operates on only the lower 4 bits of AL. This instruction will only execute if the lower 4 bits of AL are greater than 9, or if the AF flag is set.

This instruction is not valid in 64 bit mode, and if encountered, the processor will raise a #UD exception. In 16 or 32 bit mode, this instruction will only modify the AF and CF flags. The other arithmetic flags are undefined and undocumented.

Operation

This pseudo-code uses C# syntax. A list of the types used is available here.
public void AAA()
{
  if (((AL & 0xF) > 9) || AF)
  {
    if (PROCESSOR == 8086 ||
        PROCESSOR == 8088 ||
        PROCESSOR == 80186)
    {
      AH = AH + 1; // see note 1
      AL = AL + 6;
    }
    else
    {
      AX = AX + 0x106;
    }
  }
}
The operation of the AAA instruction

Notes

  1. According to the source code for Bochs' (/cpu/bcd.cc), this instruction is implemented differently on the 80186 and prior. This different operation is shown above.

Examples

These examples use NASM syntax.
mov ax, 0x106 ; 16 (decimal) in BCD
add al, 5     ; AX == 0x10B
aaa           ; AX == 0x202 (22 (decimal)) in BCD
; Also handles overflow into the upper 4 bits of AL
mov ax, 0x109 ; 19 (decimal) in BCD
add al, 9     ; AX == 0x112; AF == 1
aaa           ; AX == 0x208 (28 (decimal)) in BCD

Flags Affected

CF (carry flag)
Set if an adjustment is made. Cleared otherwise.
PF (parity flag)
Undefined.
AF (auxiliary flag)
Set if an adjustment is made. Cleared otherwise.
ZF (zero flag)
Undefined.
SF (sign flag)
Undefined.
OF (overflow flag)
Undefined.

Exceptions

Protected Mode

#UD
If the LOCK prefix is used.

Real-Address Mode

Same exceptions as protected mode.

Virtual-8086 Mode

Same exceptions as protected mode.

Compatibility Mode

Same exceptions as protected mode.

Long Mode

#UD
If in 64 bit mode.