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 ?
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.
The value is negative if the MSB is set. The SF (sign flag) in FLAGS is set according to that bit of the result.
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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With