check if carry flag is set

hans picture hans · Jun 29, 2010 · Viewed 23k times · Source

Using inline assembler [gcc, intel, c], how to check if the carry flag is set after an operation?

Answer

R.. GitHub STOP HELPING ICE picture R.. GitHub STOP HELPING ICE · Jun 29, 2010

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.