完整代码块
/************************************************/
//BitMap.h
#pragma
typedef struct BitMap
{
int* _pBit;//bit位的集合
int _capacity;//bit位总的个数j
int _size;//有效:bit位为1的个数
}BitMap;
//初始化
void InitBitMap(BitMap* pBmp, int totalBit);
//置1操作
void SetBitMap(BitMap* pBmp, int which);
//置0操作
void ReSetBitMap(BitMap* pBmp, int which);
//测一下当前比特位是1还是0
int TestBitMap(BitMap* pBmp, int which);
//统计1的个数
int CountBitMap(BitMap* pBmp);
//销毁
void DestroyBitMap(BitMap* pBmp);
/************************************************/
//BitMap.c
#include <malloc.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
//初始化
void InitBitMap(BitMap*pBmp, int totalBit)
{
int N = 0;
assert(pBmp);
N = (totalBit >> 5) + 1;
pBmp->_pBit = (int*)malloc(N * sizeof(int));
if (NULL == pBmp->_pBit)
{
assert(0);
return;
}
memset(pBmp->_pBit, 0, sizeof(int) * N);
pBmp->_capacity = totalBit;
pBmp->_size = 0;
}
//置1操作
void SetBitMap(BitMap* pBmp, int which)
{
int index = 0;
int pos = 0;
assert(pBmp);
if (which > pBmp->_capacity)
return;
//那个整形空间
index = (which >> 5);
//那个比特位
pos = (which % 32);
pBmp->_pBit[index] |= (1 << pos);
pBmp->_size++;
}
//置0操作
void ReSetBitMap(BitMap* pBmp, int which)
{
int index = 0;
int pos = 0;
assert(pBmp);
if (which > pBmp->_capacity)
return;
//那个整形空间
index = (which >> 5);
//那个比特位
pos = (which % 32);
pBmp->_pBit[index] &= ~(1 << pos);
pBmp->_size--;
}
//测一下当前比特位是1还是0
int TestBitMap(BitMap* pBmp, int which)
{
int index = 0;
int pos = 0;
assert(pBmp);
if (which > pBmp->_capacity)
return;
//那个整形空间
index = (which >> 5);
//那个比特位
pos = (which % 32);
return pBmp->_pBit[index] &(1 << pos);
}
//统计1的个数
int CountBitMap(BitMap* pBmp)
{
assert(pBmp);
return pBmp->_size;
}
//销毁
void DestroyBitMap(BitMap* pBmp)
{
if (pBmp->_pBit)
{
free(pBmp->_pBit);
pBmp->_pBit = NULL;
pBmp->_capacity = 0;
pBmp->_size = 0;
}
}
//测试函数
void Test_BitMap()
{
BitMap b;
InitBitMap(&b, 100);
SetBitMap(&b, 10);
SetBitMap(&b, 21);
SetBitMap(&b, 45);
SetBitMap(&b, 64);
SetBitMap(&b, 88);
printf("Count = %d\n", CountBitMap);
if (TestBitMap(&b, 21))
printf("21 bit is 1\n");
else
printf("21 bit is 0\n");
if (TestBitMap(&b, 22))
printf("22 bit is 1\n");
else
printf("22 bit is 0\n");
ReSetBitMap(&b, 21);
if (TestBitMap(&b, 21))
printf("21 bit is 1\n");
else
printf("21 bit is 0\n");
if (TestBitMap(&b, 22))
printf("22 bit is 1\n");
else
printf("22 bit is 0\n");
DestroyBitMap(&b);
}