6

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 ?

noufal
  • 940
  • 3
  • 15
  • 32

3 Answers3

7

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;
}
devnull
  • 118,548
  • 33
  • 236
  • 227
2

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;
}
raj raj
  • 1,932
  • 1
  • 14
  • 15
0

Try this

int status (unsigned no) {
  int sign = 0;

   // If Zero             // If -Ve = -1 OR If +Ve = -2
   (sign = ( no | 0 )) && ( sign = (~( ( (no << 1) >> 1 ) == no)) );

   // If +Ve
   (sign == -2) && (sign = 1);

  return sign;
}
Navnath Godse
  • 2,233
  • 2
  • 23
  • 32
  • I got it, It was quite simple It can be easly done by `return ((!!x) | (x >> 31));` – noufal May 25 '13 at 15:57
  • @noufal...Yes your code is working correct but it is not portable. It will only work for 32 bit. – Navnath Godse May 28 '13 at 05:33
  • @Navanth yes... that's correct.. but here its ok for me.. do you know how to do otherwise ? – noufal May 28 '13 at 14:45
  • @noufal...You can use `sizeof` operator as -> `return ((!!x) | (x >> (sizeof(int)*8) - 1));` but you need to compile for respective platform to get correct result. – Navnath Godse May 29 '13 at 04:16