Skip to content

Instantly share code, notes, and snippets.

@2sh
Last active September 29, 2024 10:17
Show Gist options
  • Save 2sh/544bdd50513aa68e4e0c0bc78aa30cee to your computer and use it in GitHub Desktop.
Save 2sh/544bdd50513aa68e4e0c0bc78aa30cee to your computer and use it in GitHub Desktop.
Fast least significant bit first bit array conversion in Javascript
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