1

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.

1

1 Answer 1

2

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);
    }
}

Sign up to request clarification or add additional context in comments.

4 Comments

Does this actually work? I don't think this is how you can use the arraybuffer :/ Because when I do new DataView(buffer) it returns all 0's.
"You cannot directly manipulate the contents of an ArrayBuffer;" developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/….
@LancePollard - sure thing, done. You could use Uint16 (or 32 or 64) as the access mechanism, but then you start to run into issues surrounding endianness.
@LancePollard - sorry, I thought I had updated the code. It now creates and uses a DataView

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.