jlee
jlee

Reputation: 3175

Looking for clarity on this answer involving logical operations

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.

  1. move the sign bit all the way to the right
  2. OR that bit with !x
    • positive would be 0 | 1
    • negative would be 1 | 0
  3. ! the result, which always, not matter what, ends up as 0
    • !(0 | 1) = 0
    • !(1 | 0) = 0

What am I understanding wrong?

Upvotes: 2

Views: 75

Answers (2)

dbush
dbush

Reputation: 225827

Where you're off is in #2:

  • if x is positive, x >> 31 == 0 and !x == 0 so !(0 | 0) == 1
  • if x is negative, x >> 31 == 1 and !x == 0 so !(1 | 0) == 0
  • if x is zero, x >> 31 == 0 and !x == 1 so !(0 | 1) == 0

Upvotes: 1

Bizkit
Bizkit

Reputation: 374

I think you're looking for :

size_t shift = sizeof(x) * 8 - 1;
bool ans = x | ~(1 << shift);

Upvotes: 0

Related Questions