SCLeo SCLeo - 1 year ago 74
Javascript Question

Using binary to compress boolean array

I am wondering if there is a way that allows me to store a boolean array efficiently. In my understanding, every boolean variable in JavaScript takes 1 byte or 8 bits to store. However, if I want to store a array of boolean value, 8 bits can store up to 8 boolean values actually. The rest 7 bits are wasted.

In language like C or Java, people can use bit operation like ">>", "~" to store boolean array into a int value. However, that does not work well in JavaScript since it works extremely slow in JavaScript because it needs to convert the floating number to int (See this question).

I also noticed Buffer in JavaScript which stores binary data directly. However, I cannot find a way to use it to store boolean array. I think Buffer are more focused on encoding stuff. For example, if I want to set the fifth bit of a boolean array to true, I can do

data |= 1<<4
but I cannot find a way to do so in Buffer.

Any solution?

Answer Source

You can use a Bit-Vector implementation:

var 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