Search code examples
assemblyx86masmcarryflag

What is the alternate way of doing "add" and "carry" operation in Assembly Language?


Hye! I have a question regarding Assembly Language. The instruction adc eax, ebx adds register eax, register ebx, and the contents of the carry flag, and then store the result back to eax. My question is that assume adc instructions are not allowed, then how can we write instructions that produce the exact same behaviour as adc eax, ebx.

I have written some code below but probably not correct.

   add eax, ebx
   add eax, 1

Solution

  • What you need to do is use conditional jumps to handle the carry flag. There are probably a few ways you can go about this. Here is my approach:

        push ebx             ; We want to preserve ebx. This seems lazy but it's
                             ; an easy approach.
    
        jnc carry_handled    ; If the carry is set:
        add ebx, 1           ;   Add 1 to summand. We are using
                             ;   ADD here, because INC does not
                             ;   set the carry flag.
                             ;
        jz carry_overflowed  ;   If it overflows (ebx is 0), then
                             ;   skip the addition. We don't want
                             ;   to add 0 which will clear the
                             ;   carry flag.
    carry_handled:           ; 
        add eax, ebx         ; Add the adjusted summand.
    carry_overflowed:
        pop ebx
    

    The important thing to look out for is that you want the CPU flags to be correctly set just the same as if an adc was executed. In the above approach, the jz carry_overflowed is excess if you don't care about the carry flag afterwards.