سؤال

Suppose %eax contains -20 and %ecx contains -30.
cmpl %eax, %ecx

When making this comparison, -30-(-20) = -10 so signed flag is set. Though when do you interpret the negative numbers as unsigned/signed?

Suppose %eax contains -10 and %ecx contains 20.
cmpl %eax, %ecx

In this example the -10 is interpreted as a large unsigned number and carry flag is set. Why wouldn't it be interpreted as 20-(-10)=30 and no flags are set?

هل كانت مفيدة؟

المحلول

That doesn't make sense. You have 32 bits, they're not signed or unsigned, or even really a number. That's just your interpretation of it.

cmp, like all ALU operations, sets all the flags (thereby effectively interpreting the number as signed and unsigned at the same time), which includes the carry flag (which is useful when interpreting the numbers as unsigned), the overflow flag (useful when interpreting the numbers as signed), and the sign flag (which is just a copy of the top bit of the result).

-10 and the big unsigned number (which is 4294967286), are not really different things. They're just two ways of looking at the bit pattern FFFFFFF6.

نصائح أخرى

It is a good practice to remember what is going on with the flags. However, you could just simply remember that using jge,jle,jg,gl are for signed comparison, and ja,jae,jb,jbe are for unsigned comparison.

So basically, you could just do the following for unsigned comparison:

cmp ecx,eax
ja some_label ; Jump if ecx > eax (unsigned)

And for signed comparison

cmp ecx,eax
jg  some_label ; Jump if ecx > eax (signed).

As harold said, all the flags are changed when you use the cmp instruction (Particularly: The sign flag, overflow flag, zero flag and carry flag). It is just about which flags you care about which makes the difference.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top