Skip to content

Instantly share code, notes, and snippets.

@DavidPu
Last active February 15, 2017 18:09
Show Gist options
  • Select an option

  • Save DavidPu/1b51f84e83d87c2428c7 to your computer and use it in GitHub Desktop.

Select an option

Save DavidPu/1b51f84e83d87c2428c7 to your computer and use it in GitHub Desktop.
bitmap
#include <stdlib.h>
#include <stdio.h>
#define BITS_PER_LONG (sizeof(long) * 8)
#define NBITS(x) ((((x)-1)/BITS_PER_LONG)+1)
#define OFF(x) ((x)%BITS_PER_LONG)
#define BIT(x) (1UL<<OFF(x))
#define LONG(x) ((x)/BITS_PER_LONG)
#define test_bit(bit, array) ((array[LONG(bit)] >> OFF(bit)) & 1)
#define FIRST_WORD_MASK(start) (~0UL << ((start) % BITS_PER_LONG))
#define LAST_WORD_MASK(nr) ((nr) % BITS_PER_LONG) ? (1UL << ((nr) % BITS_PER_LONG))-1 : ~0UL
void set_bit(unsigned long *map, int start, int nr)
{
unsigned long *p = map + LONG(start);
const int size = start + nr;
int bits_to_set = BITS_PER_LONG - (start % BITS_PER_LONG);
unsigned long mask_to_set = FIRST_WORD_MASK(start);
while (nr - bits_to_set >= 0) {
*p |= mask_to_set;
nr -= bits_to_set;
bits_to_set = BITS_PER_LONG;
mask_to_set = ~0UL;
p++;
}
if (nr) {
mask_to_set &= LAST_WORD_MASK(size);
*p |= mask_to_set;
}
}
static unsigned long bitmap[NBITS(100)];
void printbitmap(int start, int nr)
{
int i;
for (i = start; i < start + nr; i++) {
printf("%c", test_bit(i, bitmap) ? '1' : '0');
}
printf("\n");
}
int main(int argc, char *argv[])
{
set_bit(bitmap, 10, 50);
printbitmap(0, 100);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment