基于C语言实现位图

之前写过哈希表的一些操作,下面来介绍哈希表的一种变形——位图
位图是用来表示数字是否存在的情况

位图的优点是能够节省很多空间,但是缺点就是只能够表示数字是否存在
1.初始化操作
 12 void BitmapInit(Bitmap* bm,uint64_t capacity)
 13 {
 14     if(bm == NULL)
 15     {
 16         //非法输入
 17         return ;
 18     }
 19     bm->capacity = capacity;//capacity 表示该位图能表示的最大的数字
 20     uint64_t size = GetSize(capacity);//size表示申请内存时对应数组元素个数
 21     bm->data = (BitmapType*)malloc(sizeof(BitmapType)*size);
 22     memset(bm->data,0,sizeof(BitmapType)*size);
 23 }
 24 


2.销毁操作
 25 void BitmapDestroy(Bitmap* bm)
 26 {
 27     if(bm == NULL)
 28     {
 29         return ;
 30     }
 31     bm->capacity = 0;
 32     free(bm->data);
 33     return ;
 34 }

3.
 39 void GetOffset(uint64_t index,uint64_t* n,uint64_t* offset)
 40 {
 41     *n = index/(sizeof(BitmapType)*8);
 42     *offset = index%(sizeof(BitmapType)*8);
 43     return ;
 44 }
 45 
 46 int BitmapTest(Bitmap* bm,uint64_t index)
 47 {
 48     if(bm == NULL || index >= bm->capacity)
 49     {
 50         return 0;
 51     }
 52     uint64_t n,offset;
 53     GetOffset(index,&n,&offset);
 54     uint64_t ret = bm->data[n]&(0x1ul << offset);
 55     return ret>0?1:0;
 56 }
 57 

4.将某一位设为1
 58 //将某一位设为1
 59 void BitmapSet(Bitmap* bm,uint64_t index)
 60 {
 61     if(bm == NULL)
 62     {
 63         return ;
 64     }
 65     uint64_t n,offset;
 66     GetOffset(index,&n,&offset);
 67     bm->data[n] |=(0x1ul << offset);
 68     return ;
 69 }
 70 

5.将某一位是为0
 71 //将某一位设为0
 72 void BitmapUnset(Bitmap* bm,uint64_t index)
 73 {
 74     if(bm == NULL || index >= bm->capacity)
 75     {
 76         return;
 77     }
 78     uint64_t n,offset;
 79     GetOffset(index,&n,& offset);
 80     bm->data[n]&=-(0x1ul << offset);
 81     return ;
 82 }

6.全部赋值为1
 71 //将某一位设为0
 72 void BitmapUnset(Bitmap* bm,uint64_t index)
 73 {
 74     if(bm == NULL || index >= bm->capacity)
 75     {
 76         return;
 77     }
 78     uint64_t n,offset;
 79     GetOffset(index,&n,& offset);
 80     bm->data[n]&=-(0x1ul << offset);
 81     return ;
 82 }
7.全部赋值为0
 96 //全部赋值为0
 97 void BitmapClear(Bitmap* bm)
 98 {
 99     if(bm == NULL)
100     {
101         return ;
102     }
103     uint64_t size = GetSize(bm->capacity);
104     memset(bm->data,0x0,sizeof(BitmapType)*size);                                                                                  
105     return;
106 }
107 


猜你喜欢

转载自blog.csdn.net/l_x_y_hh/article/details/80546489