Set byte if positive

Viewed 82

From the page for SETcc, I can do a test to see if a (signed) number is negative with:

test %ax, %ax
sets %r10b

And if a number is zero with:

test %ax, %ax
setz %r10b

Is there a conditional to check if something is positive. I was looking for one with ZF=0 and SF=0, if that exists. What's the suggested way to check if a (signed) number is positive?

The only thing I could think of was:

cmp %ax, $0
setg %r10b

Is there a way to do this with test ?

1 Answers

Yes, you can use

    test %ax, %ax
    setg %r10b

As you can see on the page you linked, the precise definition of the setg instruction is that it sets its operand if ZF = 0 and SF = OF, i.e. if the zero flag is clear and the sign flag equals the overflow flag. The test instruction is defined to clear the overflow flag, so in this case setg sets its operand if ZF = 0 and SF = 0, which is precisely when the value being tested was strictly positive.

Likewise you can use setle after test to set if the value was nonpositive, and in this context setge and setl are equivalent to setns and sets respectively.

The same goes for the conditional jump instructions, of course.

As usual, gcc and clang know this trick.

Related