//位图下标从0开始
public class BitMap {
//默认256的大小
private int size = 256;
private byte[] bits;
public BitMap(int size) {
if (size < 0) {
size = 256;
}
this.size = size;
this.bits = new byte[getindex(size) + 1];
}
public BitMap() {
this.bits = new byte[getindex(256) + 1];
}
//获取对应的下标
private int getindex(int index) {
return index >> 3;
}
//获取对应的位数
private int getBitIndex(int index) {
return index & 0x07;
}
/**
* 获取index上的值
* @param index
* @return
*/
public boolean getResult(int index) {
if (index > size-1 || index < 0) {
throw new ArrayIndexOutOfBoundsException();
}
return (bits[getindex(index)] & (1 << getBitIndex(index))) != 0;
}
/**
* 设置index位置为0或1
* @param index
* @param value
*/
public void add(int index, boolean value) {
if (index > size-1 || index < 0) {
throw new ArrayIndexOutOfBoundsException();
}
if (value) {
bits[getindex(index)] |= 1 << getBitIndex(index);
}else {
bits[getindex(index)] &= ~(1 << getBitIndex(index));
}
}
}