0.0.3 • Published 2 years ago

bit-arrays v0.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Bit Arrays

BitArrays are an extention of TypesArrays that enable bit-level opperations.

let bitarr = new BitArray([1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]);

for(let e of bitarr){
    console.log(e)
    // result: 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
}

let uint8 = new Uint8Array(bitarr.buffer); // int8Array [129, 255]

Note that it is not technically array-like, maning numbered indices are not possible. Instead, the method .at(n) is used to grab a value fro a certan index.

bitarr[8]    // → undefined
bitarr.at(8) // → 1

Since a TypedArray must contain a whole number of byte, a BitArray will automatically pad the end of itself if the number of bits is not a multiple of eight.

If you would prefer to pad the begining instead of the end, change the second parameter of the constructor from false to true;

let bitarr = new BitArray([1, 1, 1, 1] /*, false */); // converts to [1, 1, 1, 1, 0, 0, 0, 0]

    bitarr = new BitArray([1, 1, 1, 1], true);        // converts to [0, 0, 0, 0, 1, 1, 1, 1]

    bitarr = new BitArray([1, 1, 1, 1, 1, 1, 1, 1]);  // stays as [1, 1, 1, 1, 1, 1, 1, 1]

Getting and setting

let bitarr = new BitArray([0]) // [0, 0, 0, 0, 0, 0, 0, 0]

bitarr.set(/*what to set*/[1, 1, 0, 1, 0, 1], /*index*/ 1)

console.log(bitarr)   // [0, 1, 1, 0, 1, 0, 1, 0]

bitarr.subarray(2, 6) // [1, 0, 1, 0] (plain array, not BitArray)
bitarr.slice(2, 6)    // [1, 0, 1, 0, 0, 0, 0] (BitArray; padded after slice)