Search code examples
cbit-manipulationbitwise-operators

C program return 1 if x > 0, 0 if x = 0, or -1 x < 0


i need to write a program that will return 1 if x > 0, 0 if x = 0, or -1, if x < 0 in C using only bitwise operators.

Edit: sorry for any confusion since bitwise is what the prompt says but these are the valid operators. ! ~ & ^ | + << >> and parentheses

currently i have tried this

int positive = ((x >> 31) & 1);
int negative = !((x >> 31) & -1);
int zero = !x;
return positive | !zero | ~negative;

but it fails to return -1 properly and instead returns it when the number is positive and I am confused. Any help is appreciated.


Solution

  • edit:

    return (x >> 31) | !!x;