Category Archives: Code Tips

Next power of 2..

I came across this little snippet of code* to find the next power of 2 and found it quite helpful – from what I understand it's also very efficient compared to other methods.

 

public int NextPowerOfTwo(int inInt)
{
 inInt--;
 inInt = ( inInt >> 1 ) | inInt;
 inInt = ( inInt >> 2 ) | inInt;
 inInt = ( inInt >> 4 ) | inInt;
 inInt = ( inInt >> 8 ) | inInt;
 inInt = ( inInt >> 16 ) | inInt;
 inInt++; // Val is now the next highest power of 2.
 return inInt;
}

 

Link to original article regarding technique and actually a more detailed explanation of the method – Acius' Snippets.