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

丶灬走出姿态 提交于 2019-11-30 04:48:25

问题


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 ?


回答1:


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;
}



回答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;
}



回答3:


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;
}


来源:https://stackoverflow.com/questions/16728013/how-do-i-find-whether-a-number-is-positive-negative-or-zero-without-using-if-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!