Skip to content

Instantly share code, notes, and snippets.

@ancyrweb
Created September 14, 2017 10:18
Show Gist options
  • Save ancyrweb/81e3382291492cf7044ea51a93136545 to your computer and use it in GitHub Desktop.
Save ancyrweb/81e3382291492cf7044ea51a93136545 to your computer and use it in GitHub Desktop.
extractBits
/**
* Extracts bits out of the decimal num from msb to lsb
*
* @param num
* @param msb the most significant bit
* @param lsb the least significant bit
* @returns {number}
*/
function extractBits(num, msb, lsb) {
msb = msb || 0;
lsb = lsb || 8;
let msbCount = msb;
let mask = 255;
for(let pow = 7; msbCount > 0; msbCount--, pow--) {
mask -= Math.pow(2, pow);
}
return (num & mask) >> (8 - lsb);
}
module.exports = extractBits;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment