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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>