Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find whether a number is positive, negative or zero without using if or for? [duplicate]

I want to implement the sign and zero flag setting in microprocessor. So I need to write a function to find whether the number is positive, negative or zero without using if or for loops and also only Boolean and bitwise operators are allowed. I did the following. But how to I implement it for zero condition ?

int status (int x) {
    int sign = (x >> 31);
    return sign;
}

Any suggestions ?

like image 216
noufal Avatar asked May 24 '13 05:05

noufal


People also ask

How do you check whether a number is positive or negative or zero?

Negative numbers are always written with a '−' sign in front of them and they are counted down from zero, i.e. -1, -2, -3, -4 etc. Always look at the sign in front of a number to check if it is positive or negative. Zero, 0, is neither positive nor negative.

Which flag is used to check whether the number is positive or negative?

The value is negative if the MSB is set. The SF (sign flag) in FLAGS is set according to that bit of the result.


2 Answers

The following will return -1 for negative values, 0 for zero, 1 for positive values of x.

int status (int x) {
  int sign = (x > 0) - (x < 0); 
  return sign;
}
like image 85
devnull Avatar answered Nov 10 '22 00:11

devnull


Is this enough for your purpose?

int status(int val)
{
    int minus = (val&0x80000000)&&TRUE;
    int pos = (val&0x7FFFFFFF)&&(!(val&0x80000000));
    int r = 0 - minus + pos;
    return r;
}
like image 40
raj raj Avatar answered Nov 09 '22 23:11

raj raj