Skip to content

Instantly share code, notes, and snippets.

@gwa
Last active December 16, 2015 08:09
Show Gist options
  • Save gwa/5404020 to your computer and use it in GitHub Desktop.
Save gwa/5404020 to your computer and use it in GitHub Desktop.
get set bits in a base 10 number
/**
* 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