Search code examples
bit-manipulation

bitwise checking if a number is -1 or not


I have to make a function that check if a input number is -1 or not. here's the requirement

isTmin - returns 1 if x is the minimum, two's complement number, and 0 otherwise 
Legal ops: ! ~ & ^ | +
Max ops: 10
Rating: 1

First I try this:

int isTmin(int x) {
  return !(x^(0x01<<31));
}

this method works, but I am not allowed to use the shifting operator. any ideas how can I solve this problem w/o using shift operator?


Solution

  • int isTmin(unsigned x) {
        return !x ^ !(x+x);
    }
    

    Note that you need to use unsigned in C to get twos-complement math and proper wrapping -- with int its implemention/undefined.