I am looking at the pseudo-code: The Hidden Power of BCD Instructions. Here's a snippet of the contents of the website:
So, let's take a look at what AAA does. Here is the pseudo-code equivalent (from Intel):
IF ((AL AND 0FH) > 9) OR (AF = 1)
THEN
AL = (AL + 6) AND 0FH;
AH = (AH + 1);
AF = 1;
CF = 1;
ELSE
AF = 0;
CF = 0;
FI;enter code here
That's true for a typical Intel documentation compliant use like this one:
mov al,6
add al,9 ;al=15=0Fh
aaa ;al=21=15h => it's in decimal!
The algorithm above doesn't seem to give the result as commented in the code, so I am assuming some steps were omitted here. The comment state the following: "al=21=15h => it's in decimal!".
My interpretion of the code is as follows:
- After the add instruction, the value stored in the AL register will be 15 (0Fh).
- Since it's greater than 10, six will be added to the value and ANDed with 0Fh which will result in the 1s value being stored in the AL register ("AL = (AL + 6) AND 0FH;"). The value of the AL register should now be 05h.
- The algorithm adds one to AH registers which I assume is the carry-over, since we have ANDed and zeroed 4 bits of the AL registers ("AH = (AH + 1);").
However, there is no mention of the values stored in AH registers prior to running the line "AH = (AH + 1);". If it was initialised to zero, it'll only work for numbers under 20. Now let's assume it was initialised to zero, I'll expect the result to stored as AH=1 and AL=5, but the comment says ";al=21=15h => it's in decimal!". It seems something else was done before and after the execution of this block of code.
Can you explain to me what I am missing here?
Also, how are the CF/AF flags used here?
- I understand that the AF flag is set for when there is a carry out from bit 3. Is this used to adjust the AL register to get it to store the 15h values as mentioned in the comment? As mentioned before, the algorithm did seem to suggest that the tens value are stored in the AH registers and the ones value are stored the AL registers.
- And why is CF set here? It's for the carry over from the MSB, but I can't see any the carry-over in this particular addition/conversion.I was expecting this to be set in situations like an overflows.