/**
* index: 数据保存在数组的那个下标
* index = N / 8 = N >> 3
* position: 在这个下标元素的那个位置 0-7
* position = N % 8
*
* 例子: N = 10
* index = 1
* position = 2
*
* 修改指定位置为 1 可以用 位或 运算
* 原始: 10000000
* 将 1 << position 得到: 00000100
* 或运算之后 10000100
*
* get 用位与运算得到的结果
* 等于0 那就是不存在
* 不等于0 那就是存在
*
* clear
* 将 1 << position 得到: 00000100
* 位取反 得到 11111011
* 在位与运算 10000100 得到 10000000
*/
class Bitmap {
/**
* 需要多少位
* @param {*} maxValue
*/
constructor(maxValue) {
this.maxValue = maxValue;
// 算出要多少 Byte
this.capacity = ~~(maxValue / 8) + 1;
// 需要的数据容器
this.byte = Buffer.alloc(this.capacity);
}
add(n) {
let index = n >> 3;
let position = n % 8;
let tempBit = 1 << position;
// 位或 这样指定位置变为1
this.byte[index] = this.byte[index] | tempBit;
}
get(n) {
let index = n >> 3;
let position = n % 8;
let tempBit = 1 << position;
return (this.byte[index] & tempBit) != 0;
}
clear(n) {
let index = n >> 3;
let position = n % 8;
let tempBit = 1 << position;
this.byte[index] = this.byte[index] & ~tempBit;
}
}
let test = new Bitmap(17);
console.log(test.byte);
test.add(10);
console.log(test.byte, test.get(10));
test.clear(10);
console.log(test.byte, test.get(10));
手写 Bitmap
最新推荐文章于 2024-07-26 20:46:33 发布