位图的实现

完整代码块

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值