That's an interesting solution which appears to work correctly, returning a power of two not greater than the input.

That depends on what the original poster really wants.

Different people have posted different solution sets.

One set of solutions always returns a power of two less than the target value.

One set of solutions always returns a power of two less than **or equal to** the target value.

very nice! i do think the modified brewbuck solution will be faster if i is often a random number between 2^21 and 2^32.

Try the `power_of_twoe' function below with the code provided by CornedBee.

Depending on your processor, with an expected uniform distribution, it will be at least as fast as the code provided by iMalc.

Depending on your processor, with an expected uniform distribution, you can use the `power_of_twoe' function below with a 256 byte table and it will be at least as fast as the code provided by iMalc.

Soma

Code:

unsigned int power_of_twoe
(
unsigned int i
)
{
int l(i & (i-1));
if(!l)
{
return(i >> 1);
}
if((1 << 16) > i)
{
if((1 << 8) > i)
{
return(power_of_two(i));
}
return(power_of_two(i >> 8) << 8);
}
if((1 << 24) > i)
{
return(power_of_two(i >> 16) << 16);
}
return(power_of_two(i >> 24) << 24);
}