Created
September 5, 2013 21:39
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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