8000 Add BooleanBitSet · AllAlgorithms/java@210f65c · GitHub
[go: up one dir, main page]

Skip to content
8000

Commit 210f65c

Browse files
gab1oneabranhe
authored andcommitted
Add BooleanBitSet
1 parent 0197663 commit 210f65c

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

bit-manipulation/BooleanBitSet.java

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
2+
/**
3+
* BooleanBitSet that encodes bits in longs, thus saving memory compared to a
4+
* boolean[] array.
5+
*/
6+
public class BooleanBitSet {
7+
8+
final long[] storage;
9+
10+
public BooleanBitSet(int size) {
11+
storage = new long[(int)Math.ceil(size / 64.0)];
12+
}
13+
14+
public void set(int adress, boolean value){
15+
16+
// translate adress to holding long
17+
int pos = (int)Math.floor(adress/ 64.0);
18+
long holder = storage[pos];
19+
int offset = adress % 64;
20+
21+
if(value){
22+
holder |= 1 << offset;
23+
} else {
24+
holder &= ~(1 << offset);
25+
}
26+
storage[pos] = holder;
27+
}
28+
29+
public boolean get(int adress){
30+
31+
long holder = storage[(int)Math.floor(adress/ 64.0)];
32+
int offset = adress % 64;
33+
34+
return ((holder >> offset) & 1) == 1;
35+
}
36+
37+
public static void main(String...strings){
38+
39+
BooleanBitSet b = new BooleanBitSet(20);
40+
b.set(0, true);
41+
b.set(1, true);
42+
b.set(3, true);
43+
b.set(5, true);
44+
45+
System.out.println(b.get(0));
46+
System.out.println(b.get(1));
47+
System.out.println(b.get(2));
48+
System.out.println(b.get(3));
49+
System.out.println(b.get(4));
50+
System.out.println(b.get(5));
51+
System.out.println(b.get(6));
52+
}
53+
54+
55+
56+
}

0 commit comments

Comments
 (0)
0