Last active
December 16, 2015 08:09
-
-
Save gwa/5404020 to your computer and use it in GitHub Desktop.
get set bits in a base 10 number
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
/** | |
* Returns an array of set bits in a base 10 number. | |
* @param int base10 | |
* @return Array | |
*/ | |
var getSetBits = function ( base10 ) | |
{ | |
if (!base10) { | |
return; | |
} | |
// get highest set bit | |
var hsb = 1; | |
if (base10 > 1) { | |
while (hsb < base10) { | |
hsb *= 2; | |
} | |
if (base10%2) { | |
hsb /= 2; | |
} | |
} | |
// add section for each set bit | |
var a = []; | |
while (hsb >= 1) { | |
if (hsb & base10) { | |
a.push(hsb); | |
} | |
hsb /= 2; | |
} | |
return a; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment