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

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

isPositive - return true if x > 0, otherwise false

Example: isPositive(-1)

Legal ops:

12条回答
  •  遥遥无期
    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;
    

提交回复
热议问题