Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are the carry flags set by x86 negation (NEG) / subtraction (SUB)?

What is meant by "Applying the NEG instruction to a nonzero operand always sets the Carry flag."

Why does substracting 2 from 1 set the carry flag?

           00000001 (1)
 +         11111110 (-2) [in 2-complement form]
 ---------------------
CF:1       11111111 (-1) [ why is the carry flag set here???]
like image 665
user2453180 Avatar asked Jul 21 '13 19:07

user2453180


2 Answers

You could view NEG a as equivalent to SUB 0, a. If a is non-zero, then this will set the carry flag (as this will always result in an unsigned overflow).

like image 184
Oliver Charlesworth Avatar answered Oct 19 '22 13:10

Oliver Charlesworth


  • First, we are know when a < b, a - b can always produce a carry(Borrow).

  • Second, let's understand why x86 inverted the carry flag when subtracting.
    The first point for is so obvious a human being, but not so for a computer. (Suppose computer use a + (~b+1) to replace the a - b to do calculation.) How computer figure out there is a borrow ? We can take 2's complements as a clock.(Clockwise means the original number -- a, anticlockwise means inversion --~b+1)
    enter image description here
    So for a computer, it can tell that (for subtraction) if a > b, a + ~b + 1 will have carry (overlap in the picture); if a < b, a + ~b + 1 will not have carry (gap in the picture).

  • Conclusion:
    So for subtraction, if there is no carry means there is borrow; if there is carry means no borrow, ie invert the carry bit.

By the way, as far as I have tried, there is no overflow (ie, OF is not set when 1 - 2.) I don't think @Oliver is right in this point.

like image 45
Tony Avatar answered Oct 19 '22 13:10

Tony