BitArray

BitArray

BitArray class implementing the JS TypedArray interface for a binary array.

Constructor

new BitArray(buf) → {BitArray}

Constructor for BitArray

This allows you to provide either an ArrayBuffer with pre-existing data or a requested bit-size of the BitArray.

Source:
Parameters:
Name Type Description
buf ArrayBuffer | number

Either an existing buffer containing data or a number indicating the size of the BitArray

Returns:
Type:
BitArray
Examples

Setting up BitArray with requested number of bits

const arr = new BitArray(32);

Setting up BitArray from another ArrayBuffer

const u8_arr = new Uint8Array([255, 230]);
const arr = new BitArray(u8_arr.buffer);

Classes

BitArray

Members

length

Size of BitArray

Source:
Example

Getting the length of BitArray

// returns 16
const u8_arr = new Uint8Array([255, 0]);
const arr = new BitArray(u8_arr.buffer);
arr.length

Methods

getBit(idx) → {number}

Get the bit (0 or 1) at bit index idx

Source:
Parameters:
Name Type Description
idx number

Bit index

Returns:
Type:
number

0 or 1 depending on if bit at idx is set

Examples

Getting a bit at index 0 with getBit

// returns 1
const u8_arr = new Uint8Array([255, 0]);
const arr = new BitArray(u8_arr.buffer);
arr.getBit(0)

Getting a bit at index 0 with []

// returns 1
const u8_arr = new Uint8Array([255, 0]);
const arr = new BitArray(u8_arr.buffer);
arr[0]

set(array)

Wrapper around BitArray.setArray to ensure further compliance to TypedArray interface.

Source:
See:
  • setArray for further information.
Parameters:
Name Type Description
array ArrayLike | Array

setArray(array)

Set the BitArray to array

Source:
Parameters:
Name Type Description
array ArrayLike | Array.<number> | BitArray

An array of binary data

Example

Set the BitArray to another binary array

const arr = new BitArray(4);
arr.setArray([1, 0, 0, 0);

setBit(idx, valnullable)

Set the bit at bit index idx

Note: Non-zero val will set the bit to 1. 0 or undefined val will set the bit to 0.

Source:
Parameters:
Name Type Attributes Description
idx number

Bit index to set bit

val number <nullable>

Value of bit to set (0 or 1)

Example

Set the bit at index 0 to 1

const u8_arr = new Uint8Array([255, 0]);
const arr = new BitArray(u8_arr.buffer);
arr.setBit(0, 1);

subarray(startnullable, stopnullable) → {Array.<number>}

Returns the binary array from [start, stop)

Note: if start and stop aren't provided, this will return the entire array from [0, array.length].

Source:
Parameters:
Name Type Attributes Description
start number <nullable>

Start bit index

stop number <nullable>

Stop bit index

Returns:
Type:
Array.<number>

Binary array in [start, stop)

Example

Get the subarray from 0 to 4

// returns [1, 1, 1, 1]
const u8_arr = new Uint8Array([255, 0]);
const arr = new BitArray(u8_arr);
arr.subarray(0, 4);