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

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

isPositive - return true if x > 0, otherwise false

Example: isPositive(-1)

Legal ops:

相关标签:
12条回答
  • 2020-12-14 10:38

    You have another option here:

    int is_positive = (0&x^((0^x)&-(0<x)));
    

    It is just a (0 & min(0,x)).

    Test here

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-14 10:41

    Let's play with the sign bit: sign(~n) : 1 if n >= 0

    To get rid of the case when n is 0: sign(~n + 1) : 1 if n > 0 or n = MIN_INT

    So, we want the case when both functions return 1:

    return ((~n & (~n + 1)) >> 31) & 1;
    
    0 讨论(0)
  • 2020-12-14 10:44
    int isPositive(int x)
    {
     return (!(x & 0x80000000) & !!x); 
    }
    
    0 讨论(0)
  • 2020-12-14 10:49

    Why not use XOR (^)?

    Try this,

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

    It can deal with the 0 case well.

    0 讨论(0)
  • 2020-12-14 10:51
    int isPositive(int x) {
       return !((x&(1<<31)) | !x);
    }
    

    x&(1<<31 is to check if the number is negative.

    !x is to check if the number is zero.

    A number is positive if it's not negative and not zero.

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