How do I create bit array in Javascript?

后端 未结 8 730
别跟我提以往
别跟我提以往 2020-12-05 04:47

What is the best way of implementing a bit array in JavaScript?

8条回答
  •  没有蜡笔的小新
    2020-12-05 05:38

    Thanks for a wonderfully simple class that does just what I need.

    I did find a couple of edge-case bugs while testing:

    get(n) {
        return (this.backingArray[n/32|0] & 1 << n % 32) != 0
        // test of > 0 fails for bit 31
    }
    
    forEach(callback) {
        this.backingArray.forEach((number, container)=>{
            const max = container == this.backingArray.length-1 && this.length%32
                ? this.length%32 : 32;
                // tricky edge-case: at length-1 when length%32 == 0,
                // need full 32 bits not 0 bits
        for(let x=0; x

    My final implementation fixed the above bugs and changed the backArray to be a Uint8Array instead of Array, which avoids signed int bugs.

提交回复
热议问题