Evaluating if a value is negative using bitwise operators
int test_dl3(int x) {
int i;
for (i = 0; i < 32; i+=2)
if ((x & (1<
return 0;
return
1;
}
Legal ops: ! ~ & ^ | + << >>
Max ops: 12
I have a few questions similar to this one, but I'm running into
much the same problem for all of them.
The behavior of this code appears to be that its supposed to return
a 1 when the input x is negative and a zero otherwise. I have gone
through many different ways of looking at it, but they all give
about the same result so heres one example.
((x >> 31) & 1)
The issue I come across is that with the value 0x80000000 it evaluates it as -2147483648 (a negative) when it should be evaluated as a zero. Not sure how I should be approaching these problems differently. Thanks in advance
#include <iostream>
using namespace std;
int test_dl3(int x) {
int n=x>>31;
int mask=n>>31;
return ((n+mask)^mask);
}
int main() {
cout<<test_dl3(-50)<<endl;
cout<<test_dl3(0)<<endl;
cout<<test_dl3(3)<<endl;
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.