Skip to content

Instantly share code, notes, and snippets.

@carlfriess
Created October 3, 2022 22:05
Show Gist options
  • Save carlfriess/93d79163e001940f9699f8455befd3e8 to your computer and use it in GitHub Desktop.
Save carlfriess/93d79163e001940f9699f8455befd3e8 to your computer and use it in GitHub Desktop.
Simple bitmap data structure
#ifndef BITMAP_H
#define BITMAP_H
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
typedef uint32_t bitmap_t;
static inline bitmap_t *bitmap_alloc(size_t n) {
return calloc((n >> 5) + (n & 0x1f ? 1 : 0), sizeof(bitmap_t));
}
static inline void bitmap_clear(bitmap_t *bitmap, size_t n) {
memset(bitmap, 0, ((n >> 5) + (n & 0x1f ? 1 : 0)) * sizeof(bitmap_t));
}
static inline bool bitmap_is_bit_set(const bitmap_t *bitmap, size_t bit) {
bitmap_t cell = bitmap[bit >> 5];
return (cell >> (bit & 0x1f)) & 1;
}
static inline void bitmap_set_bit(bitmap_t *bitmap, size_t bit) {
bitmap[bit >> 5] |= 1UL << (bit & 0x1f);
}
static inline void bitmap_clear_bit(bitmap_t *bitmap, size_t bit) {
bitmap[bit >> 5] &= ~(1UL << (bit & 0x1f));
}
#endif //BITMAP_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment