手写 Bitmap

/**
 *  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));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值