Last active
September 29, 2024 10:17
-
-
Save 2sh/544bdd50513aa68e4e0c0bc78aa30cee to your computer and use it in GitHub Desktop.
Fast least significant bit first bit array conversion in Javascript
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
function numToBits(num, length=8) | |
{ | |
const bits = Array(length) | |
for (let i=0; i<length; i++) | |
{ | |
bits[i] = n >> i & 1 | |
} | |
return bits | |
} | |
function bitsToNum(bits) | |
{ | |
let num = 0 | |
for (let i=0; i<bits.length; i++) | |
{ | |
num = num << 1 | bits[i] | |
} | |
return num | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment