Reputation: 3175
I'm working on a homework problem and I already got the answer correct, but it was the result of adding operators out of frustration so I'm hoping someone can clarify this for me.
I'm testing to see if a number is positive or negative, return 1 if x > 0, return 0 otherwise. Only using the bit operations ! ~ & ^ | + << >>
Here's my answer: !(x >> 31 | !x)
When I work this out on paper my understanding of it falls apart.
What am I understanding wrong?
Upvotes: 2
Views: 75
Reputation: 225827
Where you're off is in #2:
Upvotes: 1
Reputation: 374
I think you're looking for :
size_t shift = sizeof(x) * 8 - 1;
bool ans = x | ~(1 << shift);
Upvotes: 0