Lance Pollard
Lance Pollard

Reputation: 79278

How to add and remove individual bits from an ArrayBuffer in JavaScript?

I know you can't really manipulate the ArrayBuffer, but perhaps using a DataView or something like that, you could solve the problem of how to build a binary string one bit at a time. My goal is to build an encoding binary string one bit at a time, how do I do that in JavaScript? Everything I've seen only goes as far down as a Uint8Array using bytes, but I want bits.

Upvotes: 1

Views: 1076

Answers (1)

enhzflep
enhzflep

Reputation: 13099

Error checking of any nature is left as an exercise for the reader.

"use strict";
window.addEventListener('DOMContentLoaded', DOMContentLoaded, false);

function DOMContentLoaded(evt)
{
    let result = new bitBuffer(8);
    
    let _255 = [1,1,1,1,1,1,1,1];
    let _128 = [1,0,0,0,0,0,0,0];
    let _001 = [0,0,0,0,0,0,0,1];

    // make 3 entries
    for (var i=0; i<8; i++)
        result.pushBit(_255[i]);
        
    for (var i=0; i<8; i++)
        result.pushBit(_128[i]);
        
    for (var i=0; i<8; i++)
        result.pushBit(_001[i]);
        
    console.log( Array.from( result.getValue() ) );
}

class bitBuffer
{
    constructor(numBytes)
    {
        this.buffer = new ArrayBuffer(numBytes);
        this.view = new DataView( this.buffer );
        this.numBitsDone = 0;
        this.numBytesDone = 0;
    }
    pushBit(bitIsSet=false)
    {
        let curByte = this.view.getUint8( this.numBytesDone );

        curByte <<= 1;
        if (bitIsSet)
            curByte |= 0x01;

        this.view.setUint8( this.numBytesDone, curByte );
            
        this.numBitsDone++;
        if (this.numBitsDone == 8)
        {
            this.numBitsDone = 0;
            this.numBytesDone++;
        }
    }
    getValue()
    {
        return new Uint8Array(this.view.buffer);
    }
}

Upvotes: 2

Related Questions