- Teach you something new
- Do something in a novel way
- Inspire new approaches to old problems
If you don't know how it works, don't be afraid to post it. Posting a snippet that you don't understand will give people an opportunity to dissect it, and that way everyone benefits.
So, post your "Spiffy Snippet".
Mine is:
Code: Select all
uint32_t next_power_of_2(uint32_t x) {
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x++;
return x;
}
Finds the next power of two, or returns x number if it is a power of two.
Why it works:
It relies on the base-2 nature of computation with computers.
The sequence of right shifts, and OR's results in every bit, upto (exclusive) the highest bit in x being set.
Then adds one more, to force a "roll over", to the next power of two (or your original number because of the initial x--).
Cheap diagram:
Code: Select all
starting x:
+-------------------------------------------------+
| ... | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0 |
+-------------------------------------------------+
x--:
+-------------------------------------------------+
| ... | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 0 | 1 | 1 | 1 |
+-------------------------------------------------+
after shifts:
+-------------------------------------------------+
| ... | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
+-------------------------------------------------+
x++:
+-------------------------------------------------+
| ... | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+-------------------------------------------------+
I was implementing a simple hash table, and wanted an "efficient" way of calculating the next power of two.
I was unsatisfied with the readily apparent approach which is:
Code: Select all
int y=log(x)/log(2);
y++; y=pow((double)y,2.0);
I didn't find the code on my own, I was googling for alternative ways of calculating the next power of two when I found this.
I had to spend quite a few hours working it out on a whiteboard until I was confident I knew what was happening.