Carry flag in substraction
Asked Answered
W

2

5

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.

Wastage answered 2/9, 2012 at 16:29 Comment(1)
Is it 8086 programming or what?Failsafe
A
6
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.

Angary answered 2/9, 2012 at 17:6 Comment(3)
Surely all x86's act the same with regards to inverting the carry-out when subtracting?Stopped
right, that is why I edited it to say processor family. What I mean is if you compare the carry flag between x86, arm, avr, msp430, 6502, z80, etc, etc, some invert carry out, some dont. Within a family or even a company I expect them to use the same solution.Angary
Maybe I was editing it when you first saw that, and as you pointed out I dont want to create confusion that one x86 might be different than another in this regard. thanks for pointing that out +2Angary
F
1

In first case carry flag is set because you subtracted larger number from smaller one.In second case Lets suppose eax is 8 bit register then

    eax=00000101=05
    ebx=00010000=10
not ebx=11101111
         +     1
---------------------
        11110000
         +  0101
 ---------------------
        11110101

Not overflow is occurs i.e no carry flag is set.

Failsafe answered 2/9, 2012 at 17:9 Comment(1)
the hardware produces the same answer add or subtract as the same logic is used, the difference is how the carry out is handled for that processor. it sounds like this processor family (x86) inverts carry out (as well as carry in and second operand in) for a subtract but no inversions for an add.Angary

© 2022 - 2024 — McMap. All rights reserved.