Created
June 23, 2020 11:29
-
-
Save EmmanuelOga/c0d9115fc02299d954cc16b43387b840 to your computer and use it in GitHub Desktop.
Format bits on a JS number to a string
This file contains hidden or 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
| // 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