tags:

views:

1273

answers:

2

what is bitmap in c?

+1  A: 

More like that he is looking for http://en.wikipedia.org/wiki/Bit_array

Tapioca
+2  A: 

I assume you're asking how to implement a bit map (or bit array) in C. Surprisingly, the Bit_array entry on wikipedia describes the concept, but doesn't actually show how to to implement the fundamental operations, so here goes.

In short, make an array of your favorite unsigned type, and do the right arithmetic to decide how to set/clear a bit in it.

#include <limit.h>    /* for CHAR_BIT */
#include <stdint.h>   /* for uint32_t */

typedef uint32_t word_t;
enum { BITS_PER_WORD = sizeof(word_t) * CHAR_BIT };
#define WORD_OFFSET(b) ((b) / BITS_PER_WORD)
#define BIT_OFFSET(b)  ((b) % BITS_PER_WORD)

void set_bit(word_t *words, int n) { 
    words[WORD_OFFSET(n)] |= (1 << BIT_OFFSET(n));
}

void clear_bit(word_t *words, int n) {
    words[WORD_OFFSET(n)] &= ~(1 << BIT_OFFSET(n)); 
}

int get_bit(word_t *words, int n) {
    word_t bit = words[WORD_OFFSET(n)] & (1 << BIT_OFFSET(n));
    return bit != 0; 
}
Dale Hagglund