Skip to content

Instantly share code, notes, and snippets.

@EmmanuelOga
Created June 23, 2020 11:29
Show Gist options
  • Save EmmanuelOga/c0d9115fc02299d954cc16b43387b840 to your computer and use it in GitHub Desktop.
Save EmmanuelOga/c0d9115fc02299d954cc16b43387b840 to your computer and use it in GitHub Desktop.
Format bits on a JS number to a string
// Applying this mask shaves off any floating point components of the numbers.
const MASK32 = 4294967295; // = Math.pow(2, 32) - 1, or 32 ones.
function formatBits(num: number) {
const out : string[] = [];
for (let bit = 31; bit >= 0; bit--) {
out.push(num & (1 << bit) ? "1" : "0");
if (bit % 8 === 0) out.push(" ");
}
out.push(` : ${num & MASK32}`);
return out.join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment