1.位图的实现
BitMap.h
#ifndef __BITSET_H__
#define __BITSET_H__
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
typedef struct BitSet
{
char* a;
size_t N;//开辟的位个数
}BitSet;
void BitSetInit(BitSet* p, size_t n);
void BitSetDestory(BitSet* p);
//置1
void BitSetSet1(BitSet* p, size_t x);
//把1变为0
void BitSetSet0(BitSet* p, size_t x);
//判断数字是否在
int HaveNumber(BitSet* p, size_t x);
#endif
BitMap.c
#include "BitSet.h"
void BitSetInit(BitSet* p, size_t n)
{
assert(p);
p->N = n;
//确定需要的字节数,并且+1,比如33/8应该是5个字节
size_t size = (n >> 3) + 1;
//动态开辟
p->a = (char*)malloc(size);
//初始化
memset(p->a, 0, size);
}
void BitSetDestory(BitSet* p)
{
assert(p);
free(p->a);
p->a = NULL;
p->N = 0;
}
void BitSetSet1(BitSet* p, size_t x)
{
assert(p);
//计算在第几个char中
int index = x >> 3;
//第几位
int num = x % 8;
p->a[index] |= (1 << num);
}
void BitSetSet0(BitSet* p, size_t x)
{
assert(p);
int index = x >> 3;
int num = x % 8;
p->a[index] &= ~(1 << num);
}
//判断数字是否存在
int HaveNumber(BitSet* p, size_t x)
{
assert(p);
int index = x >> 3;
int num = x % 8;
int ret = p->a[index] & (1 << num);
if (0 == ret)
return 0;
else
return 1;
}
2.布隆的实现
BloomFilter.h
#ifndef __BLOOMFITER_H__
#define __BLOOMFILTER_H__
#include"BitSet.h"
typedef struct BloomFilter
{
BitSet b;
}BloomFilter;
void BloomFilterInit(BloomFilter* p,size_t n);
void BloomFilterDestory(BloomFilter* p);
void BloomFilterSet1(BloomFilter* p, char* x);
int BloomFilterHaveNumber(BloomFilter* p, char* x);
#endif
BloomFilter.c
#include"BloomFilter.h"
size_t HashFunc1(char* p)
{
assert(p);
size_t hash = 0;
while (*p)
{
hash = hash * 131 + (size_t)*p;
p++;
}
return hash;
}
size_t HashFunc2(char* p)
{
assert(p);
size_t hash = 0;
while (*p)
{
hash = hash * 31 + (size_t)*p;
p++;
}
return hash;
}
size_t HashFunc3(char* p)
{
assert(p);
size_t hash = 0;
while (*p)
{
hash = hash * 1313 + (size_t)*p;
p++;
}
return hash;
}
void BloomFilterInit(BloomFilter* p ,size_t n)
{
assert(p);
BitSetInit(&(p->b),n );
}
void BloomFilterDestory(BloomFilter* p)
{
assert(p);
BitSetDestory(&(p->b));
}
void BloomFilterSet1(BloomFilter* p, char* x)
{
assert(p);
size_t index1 = HashFunc1(x);
size_t index2 = HashFunc2(x);
size_t index3 = HashFunc3(x);
BitSetSet1(&(p->b), index1);
BitSetSet1(&(p->b), index2);
BitSetSet1(&(p->b), index3);
}
int BloomFilterHaveNumber(BloomFilter* p, char* x)
{
assert(p);
size_t index1 = HashFunc1(x);
if (HaveNumber(&(p->b), index1))
{
size_t index2 = HashFunc2(x);
if (HaveNumber(&(p->b), index2))
{
size_t index3 = HashFunc3(x);
if (HaveNumber(&(p->b), index3))
{
return 1;
}
}
}
return 0;
}