Checking whether a number is positive or negative using bitwise operators

后端 未结 16 1019
轮回少年
轮回少年 2020-12-08 20:01

I can check whether a number is odd/even using bitwise operators. Can I check whether a number is positive/zero/negative without using any conditional statements/operators l

16条回答
  •  旧时难觅i
    2020-12-08 20:31

    // if (x < 0) return -1
    // else if (x == 0) return 0
    // else return 1
    int sign(int x) {
      // x_is_not_zero = 0 if x is 0 else x_is_not_zero = 1
      int x_is_not_zero = (( x | (~x + 1)) >> 31) & 0x1;
      return (x & 0x01 << 31) >> 31 | x_is_not_zero; // for minux x, don't care the last operand 
    }
    

    Here's exactly what you waht!

提交回复
热议问题