Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a signed integer is positive?

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.

like image 533
Rowhawn Avatar asked Sep 16 '10 22:09

Rowhawn


People also ask

How do you know if a number is positive or negative?

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.

Can signed int be negative?

signed int can represent negative values, and unsigned int can only represent non-negative integer values.

Which flag is used to check if a number is positive or negative?

oVerflow (V flag): Positive + Positive is a Negative.

How do I check if a number is positive or negative in C#?

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.


2 Answers

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;
  • ...so -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);
like image 108
Matthew Slattery Avatar answered Sep 30 '22 03:09

Matthew Slattery


Check the most significant bit. 0 is positive, 1 is negative.

like image 27
Alex Avatar answered Sep 30 '22 02:09

Alex