一、概念
我们知道一个字节八个比特位,我们可以将每个字节的比特位看做一个哈希表,由低位到高位依次定下标,每个下标代表唯一的元素值,当比特位是0不存在,是1存在。
例:int a[]={1,3,7,4,12,16,19,13,22,18}
二、源代码
1、bitmap.h
#ifndef _BITMAP__H_
#define _BITMAP__H_
#include "stdio.h"
#include "assert.h"
#include "stdlib.h"
#include "string.h"
typedef struct BitMap
{
size_t* _bits;
size_t _range;
}BitMap, *pBitMap;
void BitMapInit(BitMap* bm, size_t range);
void BitMapSet(BitMap* bm, size_t x);
void BitMapReset(BitMap* bm, size_t x);
int BitMapTest(BitMap* bm, size_t x);
#endif
2、birmap.c
#include "bitmap.h"
//初始化
void BitMapInit(pBitMap bm, size_t range)
{
assert(bm);
bm->_bits = (size_t*)malloc(sizeof(size_t)*range);
memset(bm->_bits, 0, sizeof(size_t)*range);
bm->_range = range;
}
//插入
void BitMapSet(pBitMap bm, size_t x)
{
assert(bm);
size_t index = x >> 3;
size_t cur = x % 8;
bm->_bits[index] |= 1 << cur;
}
//删除
void BitMapReset(pBitMap bm, size_t x)
{
assert(bm);
size_t index = x >> 3;
size_t cur = x % 8;
bm->_bits[index] &= ~(1 << cur);
}
//查找
int BitMapTest(pBitMap bm, size_t x)
{
assert(bm);
size_t index = x >> 3;
size_t cur = x % 8;
return ((bm->_bits[index]) & (1 << cur)) == 0 ? 0 : 1;
}