Revision: 66417
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at May 3, 2014 03:01 by jscoder
Initial Code
function BitVector(data) { this.data = data == null ? [0] : data; } BitVector.prototype.and = function (other) { var data = new Array(); var newLen = Math.max(other.data.length, this.data.length); for (var i = 0; i < newLen; i++) { data[i] = this.data[i] & other.data[i]; } return new BitVector(data); } BitVector.prototype.or = function (other) { var data = new Array(); var newLen = Math.max(other.data.length, this.data.length); for (var i = 0; i < newLen; i++) { data[i] = this.data[i] | other.data[i]; } return new BitVector(data); } BitVector.prototype.xor = function (other) { var data = new Array(); var newLen = Math.max(other.data.length, this.data.length); for (var i = 0; i < newLen; i++) { data[i] = this.data[i] ^ other.data[i]; } return new BitVector(data); } BitVector.prototype.not = function () { var data = new Array(); for (var i = 0; i < this.data.length; i++) { data[i] = ~this.data[i] } return new BitVector(data); } BitVector.prototype.empty = function () { for (var i = 0; i < this.data.length; i++) { if (this.data[i] != 0) return false; } return true; } BitVector.prototype.count = function () { var c = 0; for (var i = 0; i < this.data.length; i++) { var v = this.data[i]; if (v > 0) { for (b = 0; b < 32; b++) { var bitMask = Math.pow(2, b); c += (bitMask & v) != 0; } } } return c; } BitVector.prototype.clone = function () { var data = new Array(); for (var i = 0; i < this.data.length; i++) { data[i] = this.data[i]; } return new BitVector(data); } BitVector.prototype.testBit = function (index) { var bitPos = index % 32; var val = this.data[(index - bitPos) / 32]; var bitMask = Math.pow(2, bitPos); return (bitMask & val) != 0; } BitVector.prototype.setBit = function (index, value) { var bitPos = index % 32; var bitMask = Math.pow(2, bitPos); var arrPos = (index - bitPos) / 32; if (arrPos >= this.data.length) { for (var i = this.data.length; i < arrPos + 1; i++) this.data[i] = 0; } if (value) { // Oder-Verknüpfung der Bitmask this.data[arrPos] |= bitMask; } else { // Und-Verknüpfung des Komplements der Bitmask this.data[arrPos] &= ~bitMask; } } BitVector.prototype.toString = function () { var s = ""; for (var i = 0; i < this.data.length * 32; i++) { s += this.testBit(i) ? '1' : '0'; } return s; }
Initial URL
Initial Description
Shows how to implement a primitive bit vector in js
Initial Title
BitVector in JS
Initial Tags
Initial Language
JavaScript