Boolean (Bitwise Shift Operators)

Need a boolean function using bitwise shift operators to test if an integer is even or odd.

int m = n >> 1
m = m << 1

if (n == m) then even

else

odd

---
How to write in c++?
You almost have it:
1
2
3
4
int m = n >> 1; //simply added semicolon
m = m << 1;

return n == m; //returns true if n == m, false otherwise 

You only need to add the function prototype now
I have a suggestion:

1
2
3
4
5
bool odd(int n) {
/* Returns true is n is odd */

return (n & 1)
}


The logic of it:

An odd number can be written as 2n + 1, where n is an integer (even or odd). Since all powers of two are divisible by two (i.e. can be written as 2n), except 2^0 == 1 which is odd, we can prove that an odd binary number must have its least significant bit set (end with a binary 1).


0 1 0 1 0 0 1 1
0 0 0 0 0 0 0 1 &
----------------
0 0 0 0 0 0 0 1 // The result is the integer 1, which is freely convertable to bool (true) under C++.



This might save you some cycles, although that was probably not an issue to beging with. You could also do this:

 
return (n % 2);


Which is basically the same thing but perhaps more clear.
Nice, but it doesn't conform to the OP's requirements.
Duoas, you are probably right. But I try to elaborate on these things so that I learn something myself.
Topic archived. No new replies allowed.