ADC instruction in asm

2020-07-13 13:12发布

问题:

In the following code,

MOV AL,NUMBER1
ADD AL,NUMBER2
MOV AH, 00H
ADC AH, 00H

what are lines 3 and 4 for? What do they do?

Also, why does the code clear AH? (I assume because AL's "ADD" operation may produce carry.)

回答1:

To figure this out, start by looking up what each instruction does:

  • MOV AH, 00H

    This MOV instruction will set the AH register to 0 without affecting flags.

  • ADC AH, 00H

    This ADC instruction will add the source operand (0), the carry flag (CF), and the destination operand (AH), storing the result in the destination operand (AH).

    Symbolically, then, it does: AH = AH + 0 + CF

    Remember that the MOV did not affect the flags, so the value of CF that is used by the ADC instruction is whatever was set previously by the ADD instruction (in line 2).

    Also, AH is 0 at this point, so this is really just: AH = CF.

And now you know what the code does:

  1. It moves NUMBER1 into the AL register: AL = NUMBER1

  2. It adds NUMBER2 to the AL register: AL = NUMBER1 + NUMBER2

  3. It clears AH: AH = 0

  4. It sets AH equal to CF, as set by the addition of NUMBER1 and NUMBER2. Thus, AH will be 1 if the addition required a carry, or 0 otherwise. (AH = CF)

As for the purpose of this code, it clearly performs a 16-bit addition of two 8-bit numbers. In a pseudo-C, it would basically be:

BYTE NUMBER1;
BYTE NUMBER2;
WORD RESULT = (WORD)NUMBER1 + (WORD)NUMBER2;

where the BYTE-sized inputs are extended to WORDs and added together. Why do this? Well, to handle overflow. If you add together two 8-bit values, the result may be larger than will fit in 8 bits.

The real trick to understanding this may be that the AL and AH registers are the lower and upper bits, respectively, of the AX registers. So immediately after these instructions, you may see AX being used. This contains the 16-bit result of the addition of NUMBER1 and NUMBER2.