//位圖下標從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)); } }
}