问题
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, 00HThis MOV instruction will set the
AHregister to 0 without affecting flags.ADC AH, 00HThis 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 + CFRemember that the
MOVdid not affect the flags, so the value of CF that is used by theADCinstruction is whatever was set previously by the ADD instruction (in line 2).Also,
AHis 0 at this point, so this is really just:AH = CF.
And now you know what the code does:
It moves
NUMBER1into theALregister:AL = NUMBER1It adds
NUMBER2to theALregister:AL = NUMBER1 + NUMBER2It clears
AH:AH = 0It sets
AHequal to CF, as set by the addition ofNUMBER1andNUMBER2. Thus,AHwill 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.
来源:https://stackoverflow.com/questions/44540078/adc-instruction-in-asm