Skip to content

Instantly share code, notes, and snippets.

@jmbr
Created November 8, 2010 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmbr/667605 to your computer and use it in GitHub Desktop.
Save jmbr/667605 to your computer and use it in GitHub Desktop.
Bit set data structure (C99)
/**
* @file bitset.c
* @brief Implementation of a bit set data structure.
*/
#include <stdlib.h>
#include <assert.h>
#include "bitset.h"
static inline unsigned int num_chunks(size_t length)
{
div_t d = div((int) length, UINT_BITS);
return (unsigned int) (d.rem == 0 ? d.quot : d.quot+1);
}
struct bitset *new_bitset(size_t length)
{
struct bitset *b;
size_t total_size;
if (length == 0)
return NULL;
total_size = sizeof(struct bitset) + num_chunks(length)*sizeof(unsigned);
if ((b = calloc(1, total_size)) == NULL)
return NULL;
b->length = length;
return b;
}
void delete_bitset(struct bitset *self)
{
assert(self);
free(self);
}
#ifndef BITSET_H
#define BITSET_H
/**
* @file bitset.h
* @brief Interface to the bitset data structure.
*/
#include <stdlib.h>
#include <limits.h>
#define UINT_BITS sizeof(unsigned)*CHAR_BIT
/**
* Bitset data structure.
*/
struct bitset {
size_t length; /**< Length in bits. */
unsigned chunk[]; /**< Storage for the set. */
};
extern struct bitset *new_bitset(size_t length);
extern void delete_bitset(struct bitset *self);
static inline void bitset_set(struct bitset *self, int index)
{
div_t d = div(index, UINT_BITS);
self->chunk[d.quot] |= (1 << (unsigned) d.rem);
}
static inline int bitset_get(const struct bitset *self, int index)
{
div_t d = div(index, UINT_BITS);
return (self->chunk[d.quot] >> (unsigned) d.rem) & 1;
}
static inline void bitset_clear(struct bitset *self, int index)
{
div_t d = div(index, UINT_BITS);
self->chunk[d.quot] &= ~(1 << (unsigned) d.rem);
}
#endif // !BITSET_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment