bitmap的实现方法

bitmap是一个十分有用的结构。所谓的Bit-map就是用一个bit位来标记某个元素对应的Value, 而Key即是该元素。由于采用了Bit为单位来存储数据,因此在存储空间方面,可以大大节省。

适用范围:可进行数据的快速查找,判重,删除
 
如下是实现的代码示例,用C实现,bitmap的起始位置为0
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
typedef struct bitmap {
  size_t capacity;
  char* bit_array;
}bitmap_t;

int bitmap_init(bitmap_t* bitmap, const size_t capacity) {
  if (!bitmap) {
    return -1;
  }
  //bitmap->capacity = capacity >>3 + 1;
  size_t alloc_size = capacity >>3 + 1;
  bitmap->capacity = capacity;
  char* ptr = (char*)malloc(alloc_size);
  if (!ptr) {
    return 0;
  }
  memset(ptr, 0, alloc_size);
  bitmap->bit_array = ptr;
  return 1;
}

void get_index(const int index, int* high_pos,
    char* low_pos) {
  *high_pos = index >> 3;
  *low_pos = index & 0x7;
}
int bitmap_get(const bitmap_t* bitmap, const int index) {
  int high_pos;
  char low_pos;
  get_index(index, &high_pos, &low_pos);
  if (high_pos >= bitmap->capacity) {
    return -1;
  }
  char value = bitmap->bit_array[high_pos];
  return (value &(0x1<< low_pos));
}
int bitmap_data(const bitmap_t* bitmap, const int index) {
  return 0;
}
int bitmap_set(bitmap_t* bitmap, const int index) {
  int high_pos;
  char low_pos;
  get_index(index, &high_pos, &low_pos);
  if (high_pos >= bitmap->capacity) {
    return -1;
  }
  bitmap->bit_array[high_pos] |= (1<<low_pos);

  return 0;
}

int main(int argc, char * argv[]) {
  int array[] = {0,5,8,7,6,3,1,10,78,56,34,23,
    12,43,54,65,76,87,98,89,100};
  int range = 101;
  const int len = sizeof(array)/sizeof(array[0]);
  bitmap_t bitmap;
  bitmap_init(&bitmap, range);
  for (int i = 0; i < len; ++i) {
    bitmap_set(&bitmap, array[i]);
    printf("set_value = %d
", array[i]);
  }
  for (int i = 0; i < range; ++i) {
    if (bitmap_get(&bitmap, i) > 0 ) {
      printf("get_value = %d
",i);
    }
  
  }
  return 0;
}
原文地址:https://www.cnblogs.com/westfly/p/3327030.html