1. ## bitwise operators

Hi,

I need to write a function that will return 1 if x is > 0 otherwise return 0 using only the following operations and no loops:
! ~ & ^ | + << >>

My code works for positive and negative numbers, but does not work for 0. How can I evaluate 0 as being not greater then 0?

Here is my code:
Code:
```int isPositive(int x) {

x = x >> 31;
x = x & 1;
x = !x;

return x;
}```

I'm probably missing something obvious, but no matter which way I try it, 0 always comes back as 1.

Any ideas?

2. Hello,

This is becuase the line: x = !x changes your value before returning the answer. Let's take a look step by step as x = 0:

"0 = 0 >> 31;" = 0
"0 = 0 & 1;" = 0
"0 = !0;" = 1
"return 1;"

- Stack Overflow

3. Right, 0 should be 0, not 1. But if I shift 0 to the right it is going to have the same affect as a positive number.

4. It's supposed to do that, stack overflow otherwise it would return the wrong answer for any input. It only returns the wrong answer for zero.

5. You used the '=' operator. Doesn't that violate the conditions?

6. I can use = I can't use ==

7. Code:
`   return !!x & !((x >> 31) & 1);`
The !!x will be 0 for zero and 1 for any nonzero value of x.

8. Code:
```#include <stdio.h>

int ispositive(int x)
{
return !((x >> 31) & 1) & !!x;
}

int main(void)
{
int i;

for(i = -3;i < 4;++i)
printf("%d - %d\n", i, ispositive(i));

return 0;
}```
My output:
Code:
```-3 - 0
-2 - 0
-1 - 0
0 - 0
1 - 1
2 - 1
3 - 1```
EDIT: Bah! Dave_Sinkula beat me to it

9. Code:
```int isPositive(int x)
{
return ((x + 0x7FFFFFFF) >> 31) & 1;
}```
hehe i cheated.

10. You used '=' too, Brian!

11. he said we're allowed.

12. So he did. I missed that post. Sorry.

13. Originally Posted by itsme86
So he did. I missed that post. Sorry.
there I fixed it :P

14. = yes, == no.

she not he

15. Heh,

`#define isPositive(x) ((x + 0x7FFFFFFF) >> 31 & 1)`
`#define isPositive(x) !!x & !((x >> 31) & 1)`