Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the Carry Flag set during a subtraction when zero is the minuend?

At the moment I write my own little library for arithmetic and logical operations for very big unsigned integers. To improve performance I decided to implement some functions in assembly. So here is my question. While subtracting two unsigned integers the Carry Flag is set when I subtract any number from 0.

But why is the Carry Flag set in this situation? The Carry Flag is only set when an overflow occurs, but if I subtract any number from zero I don't get an overflow. Or I am wrong?

like image 939
idlmn89 Avatar asked Jul 03 '16 03:07

idlmn89


People also ask

Why is carry flag set in subtraction?

The carry (borrow) flag is also set if the subtraction of two numbers requires a borrow into the most significant (leftmost) bits subtracted. In unsigned arithmetic, watch the carry flag to detect errors. In signed arithmetic, the carry flag tells you nothing interesting.

Would the carry flag be set?

The carry (C) flag is set when an operation results in a carry, or when a subtraction results in no borrow.

Which flags are affected after subtraction operation?

For example, if an operand is subtracted from another of equal value, the Zero flag is set. The Sign flag indicates that an operation produced a negative result. If the most significant bit (MSB) of the destination operand is set, the Sign flag is set.


1 Answers

Carry flag is carry or borrow out of the Most Significant bit (MSb):

CF (bit 0) Carry flag — Set if an arithmetic operation generates a carry or a borrow out of the mostsignificant bit of the result; cleared otherwise. This flag indicates an overflow condition for unsigned-integer arithmetic. It is also used in multiple-precision arithmetic.

Don't associate the CF with the sign bit, in a subtraction CF is set whenever the minuend, treated as unsigned, is less than the subtrahend, treated as unsigned.
This is equivalent to an overflow condition, for signed numbers the equivalent flag is OF.

For an (unnecessary?) visual clue, in this 4-5 operation, it is the second borrow, the red one, that set the CF

Borrow and CF

Not if you subtract from zero, it comes naturally that for any number, but zero itself, you'll always have the CF set, as the subtrahend has at least one bit set.


Finally, some instructions let you change the sign bit without affecting the CF (see for example the logic operations or the behavior of neg).

like image 90
Margaret Bloom Avatar answered Sep 27 '22 21:09

Margaret Bloom