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

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

isPositive - return true if x > 0, otherwise false

Example: isPositive(-1)

Legal ops:

相关标签:
12条回答
  • 2020-12-14 10:29
    int x,len;
    x = 0x0fffffff;
    len = (sizeof(x) * 8) - 2;
    
    if ((x>>len))
     printf("Negative\n");
    else
     printf("Positive\n");
    

    X will be either int or char(Integral type).

    0 讨论(0)
  • 2020-12-14 10:30

    return !((x >> 31) & 1); This is to check MSB.

    0 讨论(0)
  • 2020-12-14 10:35

    int isPositive(int x)

    {

     return ( ! (x & ( 1 << 31 ) ) );
    

    }

    It will return 1 if given no is +ve and return 0 if given no is -ve

    in this function we got sign bit if that is 1 it means no is -ve so we return 0 and if sign bit is 0 it means number is +ve so we return 1 .

    0 讨论(0)
  • 2020-12-14 10:38
    return !((x & 0x80000000) >> 31 | !x);
    
    0 讨论(0)
  • 2020-12-14 10:38

    Assuming a two’s complement representation (not always the case!), this can be achieved by testing whether the most significant bit is set (in which case the number is negative).

    Notice that the following code uses illegal operations (+, * and -) but these are for clarity and platform independence only. If you know more about your particular platform, e.g. that int is a 32 bit number, the relevant constants can be replaced by their numeric value.

    // Will be 1 iff x < 0.
    int is_neg = (x & (INT_MAX + 1)) >> (CHAR_BIT * sizeof(int) - 1);
    // Will be 1 iff x != 0.
    int is_not_zero = !!x;
    return !is_neg & is_not_zero;
    
    0 讨论(0)
  • 2020-12-14 10:38

    Haven't done assembler for quite a while, but as far as I remember first digit in the word represents negative value e.g. 1000 is -8, hence if most significant bit is 1 the number is negative. So the answer is !(x>>31)

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