Created
November 15, 2020 14:09
-
-
Save loilo/4f4f99275e5fb03120898f46ca9ed931 to your computer and use it in GitHub Desktop.
Create Array From Bitmask
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
/** | |
* Convert a bitmask to an array of its individual bits | |
* | |
* @param {number} bitmask The bitmask to dissect | |
* @return {number[]} | |
* | |
* @example | |
* assert.equal(bitmaskToArray(0b101), [0b100, 0b001]) | |
*/ | |
export function bitmaskToArray(bitmask) { | |
if (!Number.isInteger(bitmask) || bitmask < 0) { | |
throw new TypeError(`Bitmask needs to be a non-negative integer, got ${bitmask}`) | |
} | |
let array = [] | |
let upperBoundOrder = 0 | |
while (2 ** upperBoundOrder <= bitmask) { | |
let upperBound = 2 ** upperBoundOrder | |
if (upperBound & bitmask) { | |
array.push(upperBound) | |
} | |
upperBoundOrder++ | |
} | |
return array | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment