雜湊變形——點陣圖
阿新 • • 發佈:2018-11-10
一、介紹:
點陣圖就是用一個bit位表示一個數的存放狀態,適用於處理海量資料,可以大幅度減少空間。
二、圖解
三、程式碼實現
- BitMap.h
#ifndef __BITMAP_H__
#define __BITMAP_H__
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
typedef struct BitMap
{
size_t* _bits;
size_t _range;
}BitMap;
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);
void BitMapDestroy(BitMap* bm);
#endif __BITMAP_H__
- BitMap.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "Bitmap.h"
//初始化
void BitMapInit(BitMap* bm, size_t range)
{
assert(bm);
bm->_range = range;
bm->_bits = (size_t*)malloc(sizeof(size_t)*((range >> 5 ) + 1));
//sizeof(size_t):每個size_t的位元組大小
//(range >> 5) + 1:需要幾個size_t
assert(bm->_bits);
memset(bm->_bits, 0, sizeof(size_t)*((range >> 5) + 1));
}
//將x所在的位置置為1
void BitMapSet(BitMap* bm, size_t x)
{
assert(bm);
size_t index = x >> 5; //下標
size_t num = x % 32 ; //位置
bm->_bits[index] |= (1 << num);
}
//將x所在的位置置為0
void BitMapReset(BitMap* bm, size_t x)
{
assert(bm);
size_t index = x >> 5;
size_t num = x % 32;
bm->_bits[index] &= ~(1 << num);
}
//檢測x是否存在
int BitMapTest(BitMap* bm, size_t x)
{
assert(bm);
size_t index = x >> 5;
size_t num = x % 32;
return ((bm->_bits[index] & (1 << num)) == 0) ? 0 : 1;
}
//銷燬
void BitMapDestroy(BitMap* bm)
{
assert(bm);
free(bm->_bits);
bm->_bits = NULL;
bm->_range = 0;
}
- Test.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "Bitmap.h"
int main()
{
BitMap bm;
BitMapInit(&bm, 10);
BitMapSet(&bm, 1);
BitMapSet(&bm, 3);
BitMapSet(&bm, 5);
printf("%d\n", BitMapTest(&bm, 1));
printf("%d\n", BitMapTest(&bm, 3));
printf("%d\n", BitMapTest(&bm, 5));
printf("%d\n", BitMapTest(&bm, 7));
BitMapReset(&bm, 1);
BitMapReset(&bm, 3);
BitMapReset(&bm, 5);
BitMapReset(&bm, 7);
printf("%d\n", BitMapTest(&bm, 1));
printf("%d\n", BitMapTest(&bm, 3));
printf("%d\n", BitMapTest(&bm, 5));
printf("%d\n", BitMapTest(&bm, 7));
BitMapDestroy(&bm);
system("pause");
return 0;
}