amont
amont

Reputation: 101

bit manipulation to specific subset

Considering the following code snippet.

    for (int state = 1; state < 1 << n; state ++ )
        if (state & 1)
            for (int t = state; t; t &= t - 1)  

The first for-loop is to enumerate all subsets of n elements, but what subset does the t represent.

Upvotes: 0

Views: 115

Answers (1)

Spencer
Spencer

Reputation: 2214

for (int t = state; t; t &= t - 1)  

This loop is removing the least-significant 1 bits from t, one by one.

So an initial value of state like 63 (binary 111111) would go to 62 (111110), then 60, (111100), 56 (111000), 48 (110000), 32, (100000), and finally 0.

Upvotes: 4

Related Questions