Skip to content

Instantly share code, notes, and snippets.

@colematt
Created November 20, 2023 17:47
Show Gist options
  • Save colematt/7ce57add13b11364465218d4788e7109 to your computer and use it in GitHub Desktop.
Save colematt/7ce57add13b11364465218d4788e7109 to your computer and use it in GitHub Desktop.
[Generate the next number with a given number of set bits] #c
#include <stdint.h> // uint64_t
#include <stdio.h> // printf
uint64_t twiddle(uint64_t x) {
uint64_t smallest, ripple, new_smallest, ones;
if (x == 0)
return 0;
smallest = (x & -x);
ripple = x + smallest;
new_smallest = (ripple & -ripple);
ones = ((new_smallest / smallest) >> 1) - 1;
return ripple | ones;
}
int main() {
uint64_t bits = 4;
uint64_t a = 0xF; // a = 0b0000....1111
for (int i = 0; i < 100; i++) {
printf("Next number is %lu\n", (a = twiddle(a)));
}
#if 0
while (a <= 0xF000000000000000) { // a = 0b11110000...0000
printf("Next number is %lu\n", (a=twiddle(a)));
}
#endif
return 0;
}
@colematt
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment