Created
March 18, 2013 22:27
-
-
Save jhurliman/5191413 to your computer and use it in GitHub Desktop.
Store/retrieve bits in JavaScript number arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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