Lazu Razvan
Lazu Razvan

Reputation: 69

Assembly SF flag

So I have 2 registers, eax which holds 0xDEADC0DE and ebx which holds 0x1337CA5E.

The first number is bigger than the second one. However, after the cmp instruction : cmp eax, ebx the SF (sign flag) is set. Why ?

Why if the result is positive (eax - ebx) ?

Upvotes: 3

Views: 11486

Answers (1)

Johan
Johan

Reputation: 76537

cmp performs a sub (but does not keep the result).

Let's do the same by hand:

 reg     hex value   binary value    

 eax = 0xdeadc0de    ‭11011110101011011100000011011110‬
 ebx = 0x1337ca5e    ‭00010011001101111100101001011110‬
  -    ----------
 res   0xCB75F680    11001011011101011111011010000000 

The flags are set as follows:

OF (overflow) : did bit 31 change      -> no
SF (sign)     : is bit 31 set          -> yes
CF (carry)    : is abs(ebx) < abs(eax) -> no  
ZF (zero)     : is result zero         -> no
PF (parity)   : is parity of LSB even  -> no (archaic)
AF (Adjust)   : overflow in bits 0123  -> archaic, for BCD only.

As you can see, the result has bit 31 set and thus it is negative.
Just like -3 - 1 = -4 (still negative).
You cannot use the SF (sign flag) to determine if EBX > EAX. You need to use the OF (overflow flag) for signed numbers or the CF (carry flag) for unsigned numbers.

Positive or negative
The CPU does not know (or care) whether a number is positive or negative. The only person who knows is you. If you test SF and OF, then you treat the number as signed. If you only test CF then you treat the number as unsigned.
In order to help you the processor keeps track of all flags at once. You decide which flags to test and by doing so, you decide how to interpret the numbers.

Upvotes: 8

Related Questions