KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > cglib > core > TinyBitSet


1 /*
2  * Copyright 2003 The Apache Software Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package net.sf.cglib.core;
17
18 public class TinyBitSet {
19     private static int[] T = new int[256];
20     private int value = 0;
21
22     private static int gcount(int x) {
23         int c = 0;
24         while (x != 0) {
25             c++;
26             x &= (x - 1);
27         }
28         return c;
29     }
30
31     static {
32         for(int j = 0; j < 256; j++) {
33             T[j] = gcount(j);
34         }
35     }
36
37     private static int topbit(int i) {
38         int j;
39         for (j = 0; i != 0; i ^= j) {
40             j = i & -i;
41         }
42         return j;
43     }
44
45     private static int log2(int i) {
46         int j = 0;
47         for (j = 0; i != 0; i >>= 1) {
48             j++;
49         }
50         return j;
51     }
52     
53     public int length() {
54         return log2(topbit(value));
55     }
56
57     public int cardinality() {
58         int w = value;
59         int c = 0;
60         while (w != 0) {
61             c += T[w & 255];
62             w >>= 8;
63         }
64         return c;
65     }
66
67     public boolean get(int index) {
68         return (value & (1 << index)) != 0;
69     }
70
71     public void set(int index) {
72         value |= (1 << index);
73     }
74
75     public void clear(int index) {
76         value &= ~(1 << index);
77     }
78 }
79
Popular Tags