raw code

JavaScript Bit Array

Robert Eisele

Good code has to satisfy a lot of quality factors, such as readability, reusability but also performance. Especially online users aren't known for their patience. That's why writing code with very low level algorithms can speed up things a lot. To abstract all this hacking a bit, I publish a package called BitSet.js today.

The library makes it easy to work with bit vectors of any size. Integers on the other hand have the limitation of 32 or 64 bit - and in JavaScript just 31 usable bits. So check it out!

Download BitSet.js

In fact, it's really the same as working with integers directly, but with the benefit of not worrying about the size of the bit-range.

Take the following example:

var a = 0;

a|= 1 << n; // Set bit at position n

a = ~a; // Invert bits

a = a & MASK; // Mask bits

It is quite handy, but not when n becomes larger than the maximum log base 2 of the integer. For large n, the following is the same as above, but much cleaner and also scalable:

var a = new BitSet;

a.set(n, 1); // Set bit at position n

a.not(); // Invert bits

a.and(MASK); // Mask bits