2009-08-04 18 views

Respuesta

34

Asumo que estás preguntando cómo poner en práctica un mapa de bits (o matriz de bits) en C. Sorprendentemente, la entrada en la wikipedia Bit_array describe el concepto, pero en realidad no muestran cómo implementar las operaciones fundamentales , así que aquí va.

En resumen, crea una matriz de tu tipo sin signo favorito y realiza la aritmética correcta para decidir cómo configurar/borrar un bit en ella.

#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; 
} 
Cuestiones relacionadas