How do I create bit array in Javascript?

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

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

相关标签:
8条回答
  • 2020-12-05 05:44

    You can easily do that by using bitwise operators. It's quite simple. Let's try with the number 75.

    Its representation in binary is 100 1011. So, how do we obtain each bit from the number? You can use an AND "&" operator to select one bit and set the rest of them to 0. Then with a Shift operator, you remove the rest of 0 that doesn't matter at the moment.

    Example:

    Let's do an AND operation with 4 (000 0010)
    
    0100 1011 & 0000 0010 => 0000 0010
    

    Now we need to filter the selected bit, in this case, was the second-bit reading right to left.

    0000 0010 >> 1 => 1
    

    The zeros on the left are no representative. So the output will be the bit we selected, in this case, the second one.

    
    var word=75;
    var res=[];
    for(var x=7; x>=0; x--){
      res.push((word&Math.pow(2,x))>>x);
    }
    console.log(res);
    
    

    The output:

    Expected:

    In case you need more than a simple number, you can apply the same function for a byte. Let's say you have a file with multiple bytes. So, you can decompose that file in a ByteArray, then each byte in the array in a BitArray.

    Good luck!

    0 讨论(0)
  • 2020-12-05 05:48

    @Commi's implementation is what I ended up using .

    I believe there is a bug in this implementation. Bits on every 31st boundary give the wrong result. (ie when index is (32 * index - 1), so 31, 63, 95 etc.

    I fixed it in the get() method by replacing > 0 with != 0.

    get(n) {
        return (this.backingArray[n/32|0] & 1 << n % 32) != 0
    }
    

    The reason for the bug is that the ints are 32-bit signed. Shifting 1 left by 31 gets you a negative number. Since the check is for >0, this will be false when it should be true.

    I wrote a program to prove the bug before, and the fix after. Will post it running out of space.

    for (var i=0; i < 100; i++) {
      var ar = new bitArray(1000);
      
      ar.on(i);
    
      for(var j=0;j<1000;j++) {
    
        // we should have TRUE only at one position and that is "i". 
        // if something is true when it should be false or false when it should be true, then report it.
    
        if(ar.get(j)) {
          if (j != i) console.log('we got a bug at ' + i);
        } 
    
        if (!ar.get(j)) {
          if (j == i) console.log('we got a bug at ' + i);
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题