Search code examples
bit-manipulationx86-64instructionsinstruction-set

how does CF(Carry flag) get set according to the computation t = a-b where a and b are unsigned integers


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?


Solution

  • 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