Using inline assembler [gcc, intel, c], how to check if the carry flag is set after an operation?
The carry (C) flag is set when an operation results in a carry, or when a subtraction results in no borrow.
To conditionally branch on the status of the carry flag (CF), you would use JC or JNC . JC will branch if the carry flag is set (CF == 1), whereas JNC will branch if the carry flag is not set (CF == 0). The mnemonics for these opcodes are simply "Jump if Carry" and "Jump if Not Carry".
Carry Flag (CY) – Carry is generated when performing n bit operations and the result is more than n bits, then this flag becomes set i.e. 1, otherwise, it becomes reset i.e. 0.
Auxiliary Carry Flag (AF) is one of the six status flags in the 8086 microprocessor. This flag is used in BCD (Binary-coded Decimal) operations. The status of this flag is updated for every arithmetic or logical operation performed by ALU.
sbb %eax,%eax
will store -1 in eax if the carry flag is set, 0 if it is clear. There's no need to pre-clear eax to 0; subtracting eax from itself does that for you. This technique can be very powerful since you can use the result as a bitmask to modify the results of computations in place of using conditional jumps.
You should be aware that it is only valid to test the carry flag if it was set by arithmetic performed INSIDE the inline asm block. You can't test carry of a computation that was performed in C code because there are all sorts of ways the compiler could optimize/reorder things that would clobber the carry flag.
With conditional jumps jc
(jump if carry) or jnc
(jump if not carry).
Or you can store the carry flag,
;; Intel syntax
mov eax, 0
adc eax, 0 ; add with carry
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With