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?
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.
The carry (C) flag is set when an operation results in a carry, or when a subtraction results in no borrow.
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.
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
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
).
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