I've recently been studying complete search with generating subsets using bit operations, so I've stumbled upon the following code:
for(int b = 0; b < (1<<n); b++) {
vector<int> subset;
for(int i = 0; i < n; i++) {
if( b&(1<<i)) subset.push_back(i);
}
//use subset here
}
This code is used to find all subsets of a set of n elements. I'm confused by the part
b&(1<<i)
Which is clearly false if the i-th bit of b is 0, but I don't see why it'd be true if the i-th bit of b is true, I mean wouldn't the result just be 2 to the power of i (which as it doesn't equal one i.e. true, should return false)?
changes:
Beside that, I noticed now that I know that any number different from zero is considered true, that N & (1<<x) == true is true if x is 0 and N is odd, or x>0 and N is even, due to the preference of == over & , so N & (1<<x) == true resolves to N & ( (1<<x) == true )