Checking whether a number is positive or negative using bitwise operators

后端 未结 16 943
轮回少年
轮回少年 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:31

    #include
    
    void main()
    {
        int n;  // assuming int to be 32 bit long
    
        //shift it right 31 times so that MSB comes to LSB's position
        //and then and it with 0x1
        if ((n>>31) & 0x1 == 1) {
            printf("negative number\n");
        } else {
            printf("positive number\n");
        }
    
        getch();
    }
    

提交回复
热议问题