node package manager


Read/write packed binary strings bit-by-bit


A class to read and write packed binary strings, bit-by-bit.

var BitString = require('bitstring');
var bits = new BitString();
bits.number()       == 10478336
bits.hex()          == '9fe30'
bits.bin()          == '10011111111000110'
bits.bytearray() // == [ 159, 227, 0 ] 

On the server, install it:

npm install bitstring

And then just require it:

var BitString = require('bitstring');

In the browser, you have a number of options. You can download this package and include bitstring.js somewhere, which will add itself as a global, window.BitString. Alternatively, if you're using something like [require.js][require_js] to wrap your modules, BitString will check for the module variable and properly set itself as module.exports.

Create a new BitString buffer. Optionally takes source data as a String, and/or an Array to use as the byte-buffer.

The size in bytes of the BitString.

The size in bits of the BitString.

Writes the bits n to the stream (bits must be supplied as a number). Supplying n=0 will write one bit. Supplying the optional parameter size treats the bits as a field with the given length.

Flushes any pending bits to the stream.

Truncates the stream to zero bits.

Flushes the bit-buffer and moves to the given byte-offset. Mode Constants:

BitString.SEEK_FROM_EOF = 2

Returns the current position of the cursor as a byte offset from the start of the stream.

Reads the next n bits from the stream.

Reads the next n bits without moving the cursor.

True if there is more data to read.

Iterates over the bytes in the BitString.

As, but over the bytes in the BitString.

As Array.reduce, but over the bytes in the BitString.

Returns the stream as an Array of bytes.

Dumps the stream as a binary string. Unlike .number(), .bin() will not cause int overflow.

Returns the stream as a hex string.

Returns the buffer as a number. Use this with obvious caution.

Dumps the stream as a string of UTF8 characters; does not flush or change cursor position.

String representation of the data-structure; if dump_buf is true, the contents of the stream will be included, but it will not flush or change cursor position.

Dumps the stream as a string; flushes the bit-buffer but leaves cursor position unchanged.