Checking whether a number is positive or negative using bitwise operators

Viewed 102298

I can check whether a number is odd/even using bitwise operators. Can I check whether a number is positive/zero/negative without using any conditional statements/operators like if/ternary etc.

Can the same be done using bitwise operators and some trick in C or in C++?

18 Answers
#include<stdio.h>
int checksign(int n)
{
    return (n >= 0 && (n & (1<<32-1)) >=0); 
}
void main()
{
  int num = 11;
  if(checksign(num))
    {
      printf("Unsigned number"); 
    }
  else
    {
      printf("signed Number");
    }
}

Without if:

string pole[2] = {"+", "-"};
long long x;
while (true){
    cin >> x;
    cout << pole[x/-((x*(-1))-1)] << "\n\n";
} 

(not working for 0)

if(n & (1<<31)) 
{
  printf("Negative number");
}
else{
  printf("positive number");
 }

It check the first bit which is most significant bit of the n number and then & operation is work on it if the value is 1 which is true then the number is negative and it not then it is positive number

Related