Checking whether a number is positive or negative using bitwise operators

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

    Signed integers and floating points normally use the most significant bit for storing the sign so if you know the size you could extract the info from the most significant bit.

    There is generally little benefit in doing this this since some sort of comparison will need to be made to use this information and it is just as easy for a processor to tests whether something is negative as it is to test whether it is not zero. If fact on ARM processors, checking the most significant bit will be normally MORE expensive than checking whether it is negative up front.

    0 讨论(0)
  • 2020-12-08 20:22

    A simpler way to find out if a number is positive or negative: Let the number be x check if [x * (-1)] > x. if true x is negative else positive.

    0 讨论(0)
  • 2020-12-08 20:23

    Can I check whether a number is positive/zero/negative without using any conditional statements/operators like if/ternary etc.

    Of course:

    bool is_positive = number > 0;
    bool is_negative = number < 0;
    bool is_zero = number == 0;
    
    0 讨论(0)
  • 2020-12-08 20:24
    if( (num>>sizeof(int)*8 - 1) == 0 )
        // number is positive
    else
       // number is negative
    

    If value is 0 then number is positive else negative

    0 讨论(0)
  • 2020-12-08 20:29

    This can not be done in a portable way with bit operations in C. The representations for signed integer types that the standard allows can be much weirder than you might suspect. In particular the value with sign bit on and otherwise zero need not be a permissible value for the signed type nor the unsigned type, but a so-called trap representation for both types.

    All computations with bit operators that you can thus do might have a result that leads to undefined behavior.


    In any case as some of the other answers suggest, this is not really necessary and comparison with < or > should suffice in any practical context, is more efficient, easier to read... so just do it that way.

    0 讨论(0)
  • 2020-12-08 20:29
    if(n & (1<<31)) 
    {
      printf("Negative number");
    }
    else{
      printf("positive number");
     }
    

    It check the first bit which is most significant bit of the n number and then & operation is work on it if the value is 1 which is true then the number is negative and it not then it is positive number

    0 讨论(0)
提交回复
热议问题