public class BitMap {
private int[] values;
public BitMap() {
this.values = new int[1];
}
public void setBit(int n, boolean value) {
int index = n / Integer.SIZE;
int offset = n % Integer.SIZE;
if (index >= values.length) {
synchronized (this) {
if (index >= values.length) {
values = Arrays.copyOf(values, values.length << 1);
}
}
}
if (value) {
values[index] = values[index] | (1 << offset);
} else {
values[index] = values[index] & (~(1 << offset));
}
}
public boolean getBit(int n) {
if (n >= 0 && n < values.length * Integer.SIZE) {
int index = n / Integer.SIZE;
int offset = n % Integer.SIZE;
return ((values[index] >> offset) & 1) == 1;
}
return false;
}
public static void main(String[] args) {
BitMap bit = new BitMap();
bit.setBit(1, true);
bit.setBit(3, true);
System.out.println(bit.getBit(1));
System.out.println(bit.getBit(2));
System.out.println(bit.getBit(3));
bit.setBit(3, false);
System.out.println("------------------------------------------------");
System.out.println(bit.getBit(1));
System.out.println(bit.getBit(2));
System.out.println(bit.getBit(3));
System.out.println("------------------------------------------------");
bit.setBit(63, true);
System.out.println(bit.getBit(63));
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結