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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)