Say I have a binary number 01100 = 12
, what's an efficient way to iterate starting with this number such that the bits already set to one remain set?
In this example the sequence would go
01100 = 12
01101 = 13 01110 = 14 01111 = 15 开发者_运维知识库11100 = 28 11101 = 29 11110 = 30 11111 = 31
Save the original value. Then every time you increment the dynamic value, or it with the original. In Java:
int orig = val;
while (true) {
System.out.println(val);
val = (val+1) | orig;
}
If you just increment and look at the binary, whenever a block of 1s gets cleared, it will also increment the 0 past the end of that block. So you can just count, and set the bits again on each iteration:
const unsigned n = 12;
unsigned i = n;
while (1) {
// print i (or whatever)
i = (i + 1) | n;
}
int origin = 12;
for (int i = 0; i < n; i++) {
if ((origin & i) != origin)
continue;
do_something(i);
}
精彩评论