Checking whether a number is positive or negative using bitwise operators

后端 未结 16 947
轮回少年
轮回少年 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条回答
  •  粉色の甜心
    2020-12-08 20:18

    It is quite simple

    It can be easily done by

    return ((!!x) | (x >> 31));
    

    it returns

    • 1 for a positive number,
    • -1 for a negative, and
    • 0 for zero

提交回复
热议问题