Skip to content

Instantly share code, notes, and snippets.

@akoluthic
Created September 5, 2013 21:39
Show Gist options
  • Save akoluthic/6456550 to your computer and use it in GitHub Desktop.
Save akoluthic/6456550 to your computer and use it in GitHub Desktop.
Javascript algorithm for rounding down an integer to the nearest power of 2 using bitwise operators
//modified from http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
//input of 1 returns 1
function nextLowestPow2(d) {
d|=d>>1;
d|=d>>2;
d|=d>>4;
d|=d>>8;
d|=d>>16;
return (d + 1) / 2;
}
nextLowestPow2(4); //returns 4
nextLowestPow2(7); //returns 4
nextLowestPow2(83); //returns 64
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment