#include <stdio.h> #include <stdlib.h> #define INT_BIT 32 typedef struct { unsigned int *table; int size; } BitMap; BitMap * bitmap_create(int max) { BitMap *bitmap = malloc(sizeof(BitMap)); bitmap->size = max / INT_BIT + 1; bitmap->table = calloc(sizeof(int), bitmap->size); return bitmap; } void bitmap_insert(BitMap *bitmap, int key) { bitmap->table[key / INT_BIT] |= (1 << (key % INT_BIT)); } void bitmap_delete(BitMap *bitmap, int key) { bitmap->table[key / INT_BIT] &= ~(1 << (key % INT_BIT)); } int bitmap_search(BitMap *bitmap, int key) { return bitmap->table[key / INT_BIT] & (1 << (key % INT_BIT)); } void bitmap_print(BitMap *bitmap) { printf("-----\n"); int i; for (i = 0; i < bitmap->size; i++) if (bitmap->table[i] != 0) printf("%d: %d\n ", i, bitmap->table[i]); printf("-----\n"); } int main(void) { BitMap *bitmap = bitmap_create(1024); bitmap_insert(bitmap, 15); bitmap_insert(bitmap, 520); bitmap_insert(bitmap, 900); bitmap_print(bitmap); printf("%d\n", bitmap_search(bitmap, 68)); printf("%d\n", bitmap_search(bitmap, 520)); return 1; }
#define SHIFT 5 #define MASK 0x1F #define INT_BIT 32 void bitmap_insert(BitMap *bitmap, int key) { bitmap->table[key >> SHIFT] |= (1 << (key & MASK)); } void bitmap_delete(BitMap *bitmap, int key) { bitmap->table[key >> SHIFT] &= ~(1 << (key & MASK)); } int bitmap_search(BitMap *bitmap, int key) { return bitmap->table[key >> SHIFT] & (1 << (key & MASK)); }