相关数据结构
typedef uint64_t BitmapType;
#define BITMAPMAXSIZE 1000
typedef struct Bitmap
{
uint64_t* data;
uint64_t capacity;
}Bitmap;
初始化
void BitmapInit(Bitmap* bm, uint64_t capacity)
{
if(bm == NULL)
{
return;
}
bm -> capacity = capacity;
uint64_t size = capacity / (sizeof(uint64_t) * 8) + 1;
bm -> data = (BitmapType*)malloc(sizeof(BitmapType) * size);
}
销毁
void BitmapDestroy(Bitmap* bm)
{
if(bm == NULL)
{
return;
}
bm -> capacity = 0;
free(bm -> data);
bm -> data = NULL;
}
将某一位设置为1
void GetOffset(uint64_t index, uint64_t* offset, uint64_t* n)
{
if(offset == NULL || n == NULL)
{
return ;
}
*n = index / (sizeof(BitmapType) * 8);
*offset = index % (sizeof(BitmapType) * 8) ;
}
void BitmapSet(Bitmap* bm, uint64_t index)
{
if(bm == NULL || index >= bm -> capacity)
{
return;
}
uint64_t n, offset;
GetOffset(index, &n, &offset);
bm -> data[n] |= (0x1lu << offset);
}
将某一位设置为0
void BitmapUnSet(Bitmap* bm, uint64_t index)
{
if(bm == NULL || index >= bm -> capacity)
{
return;
}
uint64_t offset, n;
GetOffset(index, &n, &offset);
bm -> data[n] &= ~(0x1lu << offset);
}
检测某一位是0还是1
int BitmapTest(Bitmap* bm, uint64_t index)
{
if(bm == NULL)
{
return 0;
}
uint64_t n, offset;
GetOffset(index, &n, &offset);
uint64_t ret = bm -> data[n] & (0x1lu << offset);
if(ret == 0)
{
return 0;
}
return 1;
}
将位图每一位都设置为1
void BitmapFill(Bitmap* bm)
{
if(bm == NULL)
{
return;
}
uint64_t size = bm -> capacity / (sizeof(BitmapType) * 8) + 1;
memset(bm -> data, 0xff, sizeof(uint64_t) * size);
}
将位图清零
void BitmapClean(Bitmap* bm)
{
if(bm == NULL)
{
return;
}
uint64_t size = bm -> capacity / (sizeof(BitmapType) * 8) + 1;
memset(bm -> data, 0x00, sizeof(uint64_t) * size);
}