ADC instruction in asm

前端 未结 1 1207
予麋鹿
予麋鹿 2021-02-09 23:59

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 doe

1条回答
  •  悲&欢浪女
    2021-02-10 00:38

    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.

    0 讨论(0)
提交回复
热议问题