Checking whether a number is positive or negative using bitwise operators

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

    If the high bit is set on a signed integer (byte, long, etc., but not a floating point number), that number is negative.

    int x = -2300;  // assuming a 32-bit int
    
    if ((x & 0x80000000) != 0)
    {
        // number is negative
    }
    

    ADDED:

    You said that you don't want to use any conditionals. I suppose you could do this:

    int isNegative = (x & 0x80000000);
    

    And at some later time you can test it with if (isNegative).

提交回复
热议问题