Bitwise logic.

Hello,

I'm trying to replace some computationally heavy calculations with bitwise operations. As a simple test, I'm now simply doing a number filter. First, just printing the uneven numbers:
for (i = 0; i < 100; ++i) { if (i&1) printf("%d\n", i); }
That works perfectly. Next up, printing all numbers where the second bit is active (i&2) seemed to work perfectly too. Then, I wanted numbers where the first two bits are active (i&3), which didn't work. Judging by the results, it seems to take it as ((i&1)|(i&2)), skipping only numbers where both are 0. Any 'compound number' (not a power of 2) fails.

I know why it happens (if at least one of the bits is 'both active', it returns a non-zero value), but I don't know how to get around it. Is there a way to do it?
Certainly. Make sure both bits are set in the result:
if ((i&3)==3)...
...that was a lot easier than I thought. Kind of ashamed I didn't see that one myself.

Thanks!
Topic archived. No new replies allowed.