问题
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