Do you want to hack gosper:
int c = (1<<k)-1; while (c < (1<<n)) { dostuff(c); int a = c&-c, b = c+a; c = (c^b)/4/a|b; }
Explanation:
The search for the next number with so many bits usually comes down to the case of numbers with exactly one “block of them” —numbers having a bunch of zeros, then a bunch of ones, then a bunch of zeros again in their binary decompositions.
A way to deal with such a number of “unit blocks” is to move the highest bit left by one and reset all the others as low as possible. The gosper hack works by picking the bit with the smallest set ( a ), finding the “high part” containing the bits that we don’t touch, and the “carry bit” ( b ), then creating a block from the corresponding ones whose size starts with the least significant bit.
tmyklebu Apr 10 '13 at 18:56
source share