简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM