Search code examples
assemblyx86statusmasmcarryflag

Carry flag in substraction


I am using MASM32.

With this code:

mov eax,5
sub eax,10

CF status flag will be set. But using my pencil and paper, I actually see that there is no any carry from MSB. Yes, I know that from subtraction from less number great number set CF. But I want to know why?

Because using this code:

mov eax,5
mov ebx,10
not ebx
add ebx,1
add eax,ebx

CF flag won't be ever set.


Solution

  • 5 - 10 = 5 + (-10) = 0x05 + (0xF5 + 1) = 0x05 + 0xF6 = 0xFB
    
      00000101 -- 0x05
      11110101 -- 0xF5
    + 00000001 -- 0x01
    ==========
      11111011 -- 0xFB
    

    And this continues for 16 or 32 or 64 bits 0+1+0 = 1, carry 0

    You are right in the sense that it doesnt carry out. A subtract is an add with the second operand inverted and the carry in inverted. Some processor families invert the carry out some dont. Sounds like you are looking at something that inverts the carry out on a subtract.

    So if 5 - 10 gives carry out (borrow) then try 10 - 5 on the same processor, you should not see the carry bit set (no borrow).

    Your second example is an add operation, the carry out is not inverted on any processor that I know of, further supporting the carry bit being positive logic indicating a borrow.