0

I'm new to x64-64, just a question on how does CF get set? I was reading a textbook which says:

CF: Carry flag is used when most recent operation generated a carry out of the most significant bit. Used to detect overflow for unsigned operations.

I have two questions:

Q1-suppose we used one of the add instructions to perform the equivalent of the C assignment t = a+b, where variables a, b, and t are integers (only 3 bits for simplicity), so for 011(a) + 101(b) = 1000 = 000, since we have a carry out bit 1 in the fourth digit, so CF flag will be set to 1, is my understanding correct?

Q2-if my understanding in Q1 is true, and suppose we used one of the sub instructions to perform the equivalent of the C assignment t = a-b, where a, b, and t are unsigned integers, since a, b are unsigned, we can't actually do a+(-b), and I don't get how we can make 011(a) - 101(b) carry out of the most significant bit?

  • 5 - 3 wouldn't carry so that's not a good example. – harold Jul 10 '20 at 14:08
  • @harold could you give me a good example? –  Jul 10 '20 at 14:12
  • 3 - 5 would work, in general subtracting a larger number from a smaller one – harold Jul 10 '20 at 14:17
  • @harold I have modified my question to use `011` - `101` = 3 - 5, still don't know how can we have a fouth overflow bit so that CF flag can be set? –  Jul 11 '20 at 00:05
  • related: http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt covers Carry vs. Overflow conditions/flags which are generally meaningful for unsigned vs. signed respectively. – Peter Cordes Jul 11 '20 at 06:01

1 Answers1

1

The carry flag is often called "borrow" when performing a subtraction. After a subtraction, it set if a 1 had to be borrowed from the next bit (or would have been borrowed if you used the grade-school subtraction method). The borrow flag is like a -1 in that bit position:

  011     -1 211
- 101  ->  - 101
-----      -----
           B 110
  

You can get the same result by adding a zero to the arguments, and then the carry or borrow will be the high bit of the result:

 0011 - 0101 = 0011 + (-0101) = 0011 + 1011 = 1110
Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87
  • Note that on some ISAs, the carry flag has the opposite meaning for subtraction. But on x86, yes, it's a simple borrow output as if the subtract were done this way, *not* as if adding the 2's complement inverse or something. – Peter Cordes Jul 11 '20 at 06:05