forked from AllAlgorithms/java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BooleanBitSet.java
56 lines (41 loc) · 1.26 KB
/
BooleanBitSet.java
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
45
46
47
48
49
50
51
52
53
54
55
56
/**
* BooleanBitSet that encodes bits in longs, thus saving memory compared to a
* boolean[] array.
*/
public class BooleanBitSet {
final long[] storage;
public BooleanBitSet(int size) {
storage = new long[(int)Math.ceil(size / 64.0)];
}
public void set(int adress, boolean value){
// translate adress to holding long
int pos = (int)Math.floor(adress/ 64.0);
long holder = storage[pos];
int offset = adress % 64;
if(value){
holder |= 1 << offset;
} else {
holder &= ~(1 << offset);
}
storage[pos] = holder;
}
public boolean get(int adress){
long holder = storage[(int)Math.floor(adress/ 64.0)];
int offset = adress % 64;
return ((holder >> offset) & 1) == 1;
}
public static void main(String...strings){
BooleanBitSet b = new BooleanBitSet(20);
b.set(0, true);
b.set(1, true);
b.set(3, true);
b.set(5, true);
System.out.println(b.get(0));
System.out.println(b.get(1));
System.out.println(b.get(2));
System.out.println(b.get(3));
System.out.println(b.get(4));
System.out.println(b.get(5));
System.out.println(b.get(6));
}
}