Using bitwise operators and I suppose addition and subtraction, how can I check if a signed integer is positive (specifically, not negative and not zero)? I’m sure the answer to this is very simple, but it’s just not coming to me.
Using bitwise operators and I suppose addition and subtraction, how can I check if
Share
If you really want an “is strictly positive” predicate for
int nwithout using conditionals (assuming 2’s complement):-nwill have the sign (top) bit set ifnwas strictly positive, and clear in all other cases exceptn == INT_MIN;~nwill have the sign bit set ifnwas strictly positive, or 0, and clear in all other cases includingn == INT_MIN;-n & ~nwill have the sign bit set if n was strictly positive, and clear in all other cases.Apply an unsigned shift to turn this into a 0 / 1 answer:
EDIT: as caf points out in the comments,
-ncauses an overflow whenn == INT_MIN(still assuming 2’s complement). The C standard allows the program to fail in this case (for example, you can enable traps for signed overflow using GCC with the-ftrapvoption). Castingnto unsigned fixes the problem (unsigned arithmetic does not cause overflows). So an improvement would be: