Uh oh!
There was an error while loading. Please reload this page.
forked from madrobby/bitarray.js
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbitarray.js
More file actions
Latest commit
44 lines (37 loc) · 1.58 KB
/
Copy pathbitarray.js
File metadata and controls
44 lines (37 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"use strict";
functionBitArray(size,value){
if(typeofthis==='undefined')returnnewBitArray(size,value);
if(typeofvalue==='undefined')value=0;
this.size=size;
this.field=newArray(~~((size-1)/BitArray.ELEMENT_WIDTH)+1);
for(vari=0;i<this.field.length;i++)
this.field[i]=value==0 ? 0 : (value<<BitArray.ELEMENT_WIDTH)-1;
}
// will fail for values higher than 30
BitArray.ELEMENT_WIDTH=24;
// Set a bit (1/0)
BitArray.prototype.set=function(position,value){
if(value==1)
this.field[~~(position/BitArray.ELEMENT_WIDTH)]|=1<<(position%BitArray.ELEMENT_WIDTH);
elseif(this.field[~~(position/BitArray.ELEMENT_WIDTH)]&1<<(position%BitArray.ELEMENT_WIDTH))
this.field[~~(position/BitArray.ELEMENT_WIDTH)]^=1<<(position%BitArray.ELEMENT_WIDTH);
}
// Read a bit (1/0)
BitArray.prototype.get=function(position){
return(this.field[~~(position/BitArray.ELEMENT_WIDTH)]&1<<(position%BitArray.ELEMENT_WIDTH))>0 ? 1 : 0;
}
// Iterate over each bit
BitArray.prototype.each=function(method){
for(varindex=0;index<this.size;index++)method(this.get(index),index);
}
// Returns the field as a string like "0101010100111100," etc.
BitArray.prototype.toString=function(){
varstring=this.field.map(function(ea){
varbinary=ea.toString(2);
binary=(newArray(BitArray.ELEMENT_WIDTH-binary.length+1).join('0'))+binary;
returnbinary;
}).reverse().join('');
returnstring.split('').reverse().join('').slice(0,this.size);
}
if(typeofmodule!='undefined')
module.exports=BitArray;