assemblyx86masm32carryflageflags

Setting and Clearing the Carry Flag with Addition and Subtraction


I was having difficulty clearing the carry flag but I have come up with a way to clear it using subtraction but I was wondering if there was a better way someone could share with me on how to set and clear the carry flag using addition and subtraction.

.data

    binNum1 BYTE 11111111b

    binNum2 BYTE 00000001b

.code

    main PROC

    mov al, binNum1     ; AL = 0FFh

    add al, binNum2     ; AL = 00h CF = 1

    sub al, binNum2     ; AL = FFh CF = 1

    sub al, binNum2     ; AL = FEh  CF = 0

This is what I have to set and clear the carry flag. When I first subtract binNum2 from AL I get my original value of FFh back but the Carry Flag is still set until I subtract binNum2 from AL again. It then sets AL to FEh and clears the Carry Flag.

Does anyone have a better way of clearing the carry flag?


Solution

  • The best way to clear the carry flag is to use the CLC instruction; and the best way to set the carry flag is to use the STC instruction.

    If you must do it with addition or subtraction for some bizarre reason; the least worst method (for code size) is likely sub eax,eax to clear the carry flag, and xor eax,eax; sub eax,1 to set the carry flag.

    Note: to set the carry flag, stc; sbb eax,eax would be even less bad, but that solution probably makes the pointlessness too obvious.