For example, find the smallest power of 2 that is greater than or equal to 12, 13, 15, etc.: 16; similarly, the smallest power greater than or equal to 5, 6, and 7 is 8.
//v must be a 32-bit integer int roundup_power_of_2(unsigned int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; }
More bit related algorithms:
http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2