• Stars
    star
    217
  • Rank 175,951 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 10 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An arbitrary size Bit-Vector implementation in JavaScript

BitSet.js

NPM Package

Build Status MIT license

BitSet.js is an infinite Bit-Array (aka bit vector, bit string, bit set) implementation in JavaScript. Infinite means that if you invert a bit vector, the leading ones get remembered. As far as I can tell, BitSet.js is the only library which has this feature. It is also heavily benchmarked against other implementations and is the most performant implementation to date.

Examples

Basic usage

let bs = new BitSet;
bs.set(128, 1); // Set bit at position 128
console.log(bs.toString(16)); // Print out a hex dump with one bit set

Flipping bits

let bs = new BitSet;
bs
  .flip(0, 62)
  .flip(29, 35);

let str = bs.toString();

if (str === "111111111111111111111111111000000011111111111111111111111111111") {
   console.log("YES!");
}

Range Set

let bs = new BitSet;
bs.setRange(10, 18, 1); // Set a 1 between 10 and 18, inclusive

User permissions

If you want to store user permissions in your database and use BitSet for the bit twiddling, you can start with the following Linux-style snippet:

let P_READ  = 2; // Bit pos
let P_WRITE = 1;
let P_EXEC  = 0;

let user = new BitSet;
user.set(P_READ); // Give read perms
user.set(P_WRITE); // Give write perms

let group = new BitSet(P_READ);
let world = new BitSet(P_EXEC);

console.log("0" + user.toString(8) + group.toString(8) + world.toString(8));

Installation

npm install bitset

or

bower install bitset.js

Using BitSet.js with the browser

<script src="bitset.js"></script>
<script>
    console.log(BitSet("111"));
</script>

Using BitSet.js with require.js

<script src="require.js"></script>
<script>
requirejs(['bitset.js'],
function(BitSet) {
    console.log(BitSet("1111"));
});
</script>

Constructor

The default BitSet constructor accepts a single value of one the following types :

  • String
    • Binary strings : new BitSet("010101")
    • Binary strings with prefix : new BitSet("0b010101")
    • Hexadecimal strings with prefix new BitSet("0xaffe")
  • Array
    • The values of the array are the indices to be set to 1 : new BitSet([1,12,9])
  • Uint8Array
    • A binary representation in 8 bit form
  • Number
    • A binary value
  • BitSet
    • A BitSet object, which get copied over

Functions

The data type Mixed can be either a BitSet object, a String or an integer representing a native bitset with 31 bits.

BitSet set(ndx[, value=1])

Mutable; Sets value 0 or 1 to index ndx of the bitset

int get(ndx)

Gets the value at index ndx

BitSet setRange(from, to[, value=1])

Mutable; Helper function for set, to set an entire range to a given value

BitSet clear([from[, to]])

Mutable; Sets a portion of a given bitset to zero

  • If no param is given, the whole bitset gets cleared
  • If one param is given, the bit at this index gets cleared
  • If two params are given, the range is cleared

BitSet slice([from[, to]])

Immutable; Extracts a portion of a given bitset as a new bitset

  • If no param is given, the bitset is getting cloned
  • If one param is given, the index is used as offset
  • If two params are given, the range is returned as new BitSet

BitSet flip([from[, to]])

Mutable; Toggles a portion of a given bitset

  • If no param is given, the bitset is inverted
  • If one param is given, the bit at the index is toggled
  • If two params are given, the bits in the given range are toggled

BitSet not()

Immutable; Calculates the bitwise complement

BitSet and(Mixed x)

Immutable; Calculates the bitwise intersection of two bitsets

BitSet or(Mixed x)

Immutable; Calculates the bitwise union of two bitsets

BitSet xor(Mixed x)

Immutable; Calculates the bitwise xor between two bitsets

BitSet andNot(Mixed x)

Immutable; Calculates the bitwise difference of two bitsets (this is not the nand operation!)

BitSet clone()

Immutable; Clones the actual object

Array toArray()

Returns an array with all indexes set in the bitset

String toString([base=2])

Returns a string representation with respect to the base

int cardinality()

Calculates the number of bits set

int msb()

Calculates the most significant bit (the left most)

int ntz()

Calculates the number of trailing zeros (zeros on the right). If all digits are zero, Infinity is returned, since BitSet.js is an arbitrary large bit vector implementation.

int lsb()

Calculates the least significant bit (the right most)

bool isEmpty()

Checks if the bitset has all bits set to zero

bool equals()

Checks if two bitsets are the same

BitSet.fromBinaryString(str)

Alternative constructor to pass with a binary string

BitSet.fromHexString(str)

Alternative constructor to pass a hex string

BitSet.Random([n=32])

Create a random BitSet with a maximum length of n bits

Iterator Interface

A BitSet object is iterable. The iterator gets all bits up to the most significant bit. If no bits are set, the iteration stops immediately.

let bs = BitSet.Random(55);
for (let b of bs) {
  console.log(b);
} 

Note: If the bitset is inverted so that all leading bits are 1, the iterator must be stopped by the user!

Coding Style

As every library I publish, BitSet.js is also built to be as small as possible after compressing it with Google Closure Compiler in advanced mode. Thus the coding style orientates a little on maxing-out the compression rate. Please make sure you keep this style if you plan to extend the library.

Build the library

Gulp is optional for minifying with Google Closure Compiler. After cloning the Git repository, do:

npm install
gulp

Run a test

Testing the source against the shipped test suite is as easy as

npm test

Copyright and licensing

Copyright (c) 2014-2023, Robert Eisele Dual licensed under the MIT or GPL Version 2 licenses.

More Repositories

1

jQuery-webcam

A webcam wrapper plugin for jQuery
ActionScript
515
star
2

Fraction.js

Fraction is a rational numbers library written in JavaScript
JavaScript
422
star
3

node-dhcp

A DHCP server and client written in pure JavaScript
JavaScript
292
star
4

PHP-Facedetect

A simple OpenCV wrapper for PHP to detect faces on images
C++
263
star
5

GPS.js

A NMEA parser and GPS utility library
JavaScript
243
star
6

jQuery-Paging

Probably the most advanced jQuery pagination plugin, no really!
HTML
233
star
7

Complex.js

A complex numbers library
JavaScript
224
star
8

jQuery-xcolor

An easy to use color manipulation plugin for jQuery
JavaScript
157
star
9

PHP

A PHP improvement
C
137
star
10

udf_infusion

A MySQL functionality enhancement UDF
Shell
136
star
11

Polynomial.js

A JavaScript library to work with polynomials
JavaScript
121
star
12

Quaternion.js

A JavaScript Quaternion library
JavaScript
115
star
13

Fritzing

My fritzing sketches
C++
63
star
14

node-gamecontroller

A node.js driver for several gamecontrollers
JavaScript
51
star
15

HTML5-Tetris

A HTML5 Tetris Implementation
JavaScript
45
star
16

HTML5-Experiments

My HTML5 Experiments
HTML
34
star
17

Trackball.js

A library to add a virtual Trackball to your DOM
JavaScript
34
star
18

Kalman.js

A JavaScript Kalman filter library
JavaScript
30
star
19

PHP-Daemon

PHP
30
star
20

Stewart

Inverse kinematics for Stewart Platforms written in JavaScript
JavaScript
25
star
21

Rectangles.js

Rectangles.js is a collection of functions to work with rectangles
JavaScript
20
star
22

Angles.js

Angles.js is a collection of functions to work with angles
JavaScript
17
star
23

PHP-Classes

A collection of PHP classes
PHP
15
star
24

PHP-Defcon

A global constant management library for PHP
C
14
star
25

JavaScript-Files

A collection of JavaScript files
JavaScript
11
star
26

Circle.js

A function collection for working with circles
JavaScript
11
star
27

node-dsh

A full featured JavaScript shell
JavaScript
9
star
28

PHP-IDNA

A libidn wrapper for PHP
C
5
star
29

PHP-Infusion

A PHP functionality enhancement library
C
5
star
30

PHP-Sysload

A simple sysload monitoring extension for PHP
C
3
star
31

mod_mysql_accesslog

A lighttpd module to log directly into MySQL
C
3
star
32

UnitFormat.js

A human readable unit formatting tool in JavaScript
JavaScript
2
star
33

jQuery-borderstyle

A handy jQuery plugin to manipulate the border stlye CSS attributes
JavaScript
1
star