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.
If a number is greater than zero, it is a positive number. If a number is less than zero, it is a negative number. If a number equals to zero, it is zero.
signed int can represent negative values, and unsigned int can only represent non-negative integer values.
oVerflow (V flag): Positive + Positive is a Negative.
Nested if else condition statement is used to check that given number is less than zero. If the condition is true then execute the statement and print the statement as positive. Otherwise, if the condition is false, then execute the else statement and print the statement as the number is 0.
If you really want an "is strictly positive" predicate for int n
without using conditionals (assuming 2's complement):
-n
will have the sign (top) bit set if n
was strictly positive, and clear in all other cases except n == INT_MIN
;~n
will have the sign bit set if n
was strictly positive, or 0, and clear in all other cases including n == INT_MIN
;-n & ~n
will 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:
int strictly_positive = (unsigned)(-n & ~n) >> ((sizeof(int) * CHAR_BIT) - 1);
EDIT: as caf points out in the comments, -n
causes an overflow when n == 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-ftrapv
option). Casting n
to unsigned fixes the problem (unsigned arithmetic does not cause overflows). So an improvement would be:
unsigned u = (unsigned)n;
int strictly_positive = (-u & ~u) >> ((sizeof(int) * CHAR_BIT) - 1);
Check the most significant bit. 0 is positive, 1 is negative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With