   finding the lowest power of two above n
  I am working on a function to find the lowest power of two that is greater than or equal to n. For example, if n == 11, the function returns 16. If n == 17, the function returns 32. If n == 512, it returns 512.int lowestPowerOfTwo(int n){    int result = 1;    while (result < n) result <<= 1;    return result;}This finds the right answer. I'm just curious about better solutions. The return value and n will always be integer types. (If there is a faster solution using unsigned integers, that is fine too.)   
This page has two methods. The second one is the one I was going to suggest. In your particular case, you should skip the initial decrement.;  The fastest way to do it is to use the bsr machine instruction, which calculates the integer log2 of the value in a single cycle. Visual Studio supports it with a compiler intrinsic.unsigned long nextPow2(unsigned long x){unsigned long iLog2x;if(x <= 1)return 1;_BitScanReverse(&iLog2x,x-1);return 1 << (iLog2x + 1);}The method presented on the website linked above is not 64 bit safe - some (not all) 64 bit implementations treat int as a 64 bit type. This can be handled easily enough.unsigned int nextPow2(unsigned int x){--x;x |= x >> 1;x |= x >> 2;x |= x >> 4;x |= x >> 8;x |= x >> 16;if(sizeof(int) == 8)x |= x >> 32;return ++x;}Last thing: The first method I posted returns 1 when you input 0, while other methods like the one above return 0 with input 0. The first integer power of 2 which is >= 0 is in fact 1, as 0 isn't a power of anything. Of course how you expect the function to respond to 0 is up to you.   