Check if a number x is positive (x>0) by ONLY using bitwise operators in C

后端 未结 12 610
夕颜
夕颜 2020-12-14 10:24

isPositive - return true if x > 0, otherwise false

Example: isPositive(-1)

Legal ops:

12条回答
  •  暖寄归人
    2020-12-14 10:40

    if your working with a number system that uses the MSB as the signage bit, you can do:

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

提交回复
热议问题