Skip to content

Instantly share code, notes, and snippets.

@jhurliman
Created March 18, 2013 22:27
Show Gist options
  • Save jhurliman/5191413 to your computer and use it in GitHub Desktop.
Save jhurliman/5191413 to your computer and use it in GitHub Desktop.
Store/retrieve bits in JavaScript number arrays
function BitArray(options) {
var USABLE_BITS = 32;
if (options.data) {
this.data = options.data;
} else if (options.bits) {
var count = Math.ceil(options.bits / USABLE_BITS);
this.data = new Array(count);
for (var i = 0; i < count; i++)
this.data[i] = 0;
} else {
this.data = [0];
}
this.get = function(pos) {
var idx = Math.floor((pos - 1) / USABLE_BITS);
var offset = pos - (idx * USABLE_BITS) - 1;
var mask = 1 << offset;
return +!!(this.data[idx] & mask);
};
this.set = function(pos, on) {
var idx = Math.floor((pos - 1) / USABLE_BITS);
var offset = pos - (idx * USABLE_BITS) - 1;
var mask = 1 << offset;
if (on)
this.data[idx] |= mask;
else
this.data[idx] &= ~mask;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment