Bitmap 代码示例、
/**
* @Author: subd
* @Date: 2019/8/30 7:41
* 位图算法
*/
public class MyBitmap {
//每个word是一个long类型元素,对应一个64位的二进制数据
private long[] words;
private int size;
public MyBitmap(int size) {
this.size = size;
this.words = new long[(getWordIndex(size - 1)) + 1];
}
public boolean getBit(int bitIndex) {
if (bitIndex < 0 || bitIndex > size - 1) {
throw new IndexOutOfBoundsException("超过Bitmap有效范围");
}
int wordIndex = getWordIndex(bitIndex);
return (words[wordIndex] & (1L << bitIndex)) != 0;
}
/**
* 把Bitmap 某一位置设置为true
*
* @param bitIndex 位图的第bitIndex位(bitIndex=0代表Bitmap左数第一位)
*/
public void setBit(int bitIndex) {
if (bitIndex < 0 || bitIndex > size - 1) {
throw new IndexOutOfBoundsException("超过Bitmap有效范围");
}
int wordIndex = getWordIndex(bitIndex);
words[wordIndex] |= (1L << bitIndex);
}
private int getWordIndex(int bitIndex) {
//右移6位,相当于处于64
return bitIndex >> 6;
}
public static void main(String[] args) {
MyBitmap bitmap = new MyBitmap(128);
bitmap.setBit(126);
bitmap.setBit(75);
System.out.println(bitmap.getBit(126));
System.out.println(bitmap.getBit(78));
}
}
414

被折叠的 条评论
为什么被折叠?



