isPositive
- return true
if x > 0
, otherwise false
Example: isPositive(-1)
Legal ops:
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).
return !((x >> 31) & 1); This is to check MSB.
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 .
return !((x & 0x80000000) >> 31 | !x);
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;
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)