天天看點

java中BitMap實作

參考的部落格位址:http://blog.csdn.net/xqy1522/article/details/7901141

int中32位隻能表示一個數,而用BitMap可以表示32一個數:

int[] bitMap:

bitMap[0]:可以表示數字0~31 比如表示0:00000000 00000000 00000000 00000000

比如表示1 : 00000000 00000000 00000000 00000001

bitMap[1]:可以表示數字32~63

bitMap[2]:可以表示數字64~95

……

是以要将一個數插入到bitMap中要進過三個步驟:

1)找到所在bitMap中的index也就是bitMap數組下标

比如我們要在第64一個位置上插入一個資料(也就是插入63)

index = 63 >> 5 = 1,也就是說63應該插入到bitMap[1]中

2)找到63在bitMap[1]中的偏移位置

offset = 63 & 31 = 31說明63在bitMap[1]中32位的最高位

3)将最高位設為1

具體代碼如下:

package com.xll;
/**
 * 實作BitMap
 * 
 * @author xialonglei
 * @since 2016/5/26
 */
public class BitMap {
    /** 插入數的最大長度,比如100,那麼允許插入bitsMap中的最大數為99 */
    private long length;
    private static int[] bitsMap;
    private static final int[] BIT_VALUE = { , , , , , ,
            , , , , , , , , ,
            , , , , , , , , ,
            , , , , , , ,  };
    public BitMap(long length) {
        this.length = length;
        // 根據長度算出,所需數組大小
        bitsMap = new int[(int) (length >> ) + ((length & ) >  ?  : )];
    }
    /**
     * 根據長度擷取資料 比如輸入63,那麼實際上是确定數62是否在bitsMap中
     * 
     * @return index 數的長度
     * @return 1:代表數在其中 0:代表
     */
    public int getBit(long index) {
        if (index <  || index > length) {
            throw new IllegalArgumentException("length value illegal!");
        }
        int intData = (int) bitsMap[(int) ((index - ) >> )];
        return ((intData & BIT_VALUE[(int) ((index - ) & )])) >>> ((index - ) & );
    }
    /**
     * @param index
     *            要被設定的值為index - 1
     */
    public void setBit(long index) {
        if (index <  || index > length) {
            throw new IllegalArgumentException("length value illegal!");
        }
        // 求出該index - 1所在bitMap的下标
        int belowIndex = (int) ((index - ) >> );
        // 求出該值的偏移量(求餘)
        int offset = (int) ((index - ) & );
        int inData = bitsMap[belowIndex];
        bitsMap[belowIndex] = inData | BIT_VALUE[offset];
    }
    public static void main(String[] args) {
        BitMap bitMap = new BitMap();
        bitMap.setBit();
        System.out.println(bitMap.getBit());
        System.out.println(bitMap.getBit());
    }
}
           

結果圖:

1