# Calculating the closest number power of 2 to a given number

• Dec 2nd 2010, 03:21 AM
pranay
Calculating the closest number power of 2 to a given number
Hi, i found the following way to do the required job fast, but am unable to understand how it works . Could someone please explain it.

nearest_pow (uint32_t num)
{
uint32_t n = num > 0 ? num - 1 : 0;

n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;

return n;
}
Thanks.
• Dec 2nd 2010, 11:31 PM
CaptainBlack
Quote:

Originally Posted by pranay
Hi, i found the following way to do the required job fast, but am unable to understand how it works . Could someone please explain it.

nearest_pow (uint32_t num)
{
uint32_t n = num > 0 ? num - 1 : 0;

n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;

return n;
}
Thanks.

Do you have the pseudo-code?

Do you know what /= and >> operators do?

Opps.. It seems you have "|=" (xor) not "/="

Since this is playing with the bit patterns of the function argument I would suggest that you convert some trial argument to binary and trace this. Also I would be interested in what you think the closest power of 2 means and how that compares with what this code produces.

CB
• Dec 3rd 2010, 02:45 AM
pranay
Thanks, i know about the operators but can't understand their use here to get the result.
BY nearest power of 2 i mean, suppose i have a number 6 then the next greater number which is closest to it and a power of 2 is 8.