java利用数组和位运算构建bitmap
public class BitMap {
private char[] bytes;
/**
* 定义最大值
*/
private int nbits;
public BitMap(int nbits) {
this.nbits = nbits;
this.bytes = new char[nbits / 16 + 1];
}
public void set(int k) {
if (k > nbits) {
return;
}
int byteIndex = k / 16;
int bitIndex = k % 16;
bytes[byteIndex] |= (1 << bitIndex);
}
public boolean get(int k) {
if (k > nbits) {
return false;
}
int byteIndex = k / 16;
int bitIndex = k % 16;
return (bytes[byteIndex] & (1 << bitIndex)) != 0;
}
}
为了让人更好的理解位运算请看以下小例子
System.out.println(Integer.toBinaryString(1<<1));
System.out.println(Integer.toBinaryString(1<<2));
char a = 1<<1;
a |= 1<<2;
System.out.println(Integer.toBinaryString(a ));
输出结果为
10
100
110
当然现在有直接的工具类可以使用,BitSet