-3

I have an array of size 10

I want to keep track of the free space in the array and i was told bitmap is a better option.

For e.g index 2 and 3 is empty, i could record bit 0 at index 2 and 3 in the bitmap

How do i create a bitmap of size 10 with default 0 bits?

Helpful links regarding bitmaps are welcomed.

Thanks in advance

  • Welcome to Stack Overflow. Please visit the [Help Center](https://stackoverflow.com/help) and read [How To Ask](https://stackoverflow.com/help/on-topic) – machine_1 Mar 08 '18 at 13:06
  • How many bits are there in an integer? Would that be more than 10? Wouldn't 1 bit per entry be enough? – Paul Ogilvie Mar 08 '18 at 13:12

1 Answers1

1

C doesn't have any first-class support for a "bit map" type; you're going to have to implement it yourself. It's very simple, just use an array of unsigned integers and some bitwise shifting/logic operators.

Something like:

typedef struct {
  unsigned int *bits;
  size_t size;
} bitmap;

#define BITS (CHAR_BIT * sizeof (unsigned int))

bitmap * bitmap_new(size_t size)
{
  const size_t length = (size + BITS - 1) / BITS;
  const size_t bytes = length * sizeof (unsigned int);
  bitmap *b = malloc(sizeof *b + bytes);
  if (b != NULL)
  {
    b->bits = (unsigned int *) (b + 1);
    memset(b->bits, 0, length);
    b->size = size;
  }
  return b;
}

bool bitmap_test(const bitmap *b, size_t index)
{
  if (index < b->size)
  {
    const size_t ii = index / BITS;
    const unsigned int ib = index % BITS;
    return (bool) ((b->bits[ii] & (1u << ib)) != 0);
  }
  return false;
}

void bitmap_set(bitmap *b, size_t index)
{
  if (index < b->size)
  {
    const size_t ii = index / BITS;
    const unsigned int ib = index % BITS;
    b->bits[ii] |= (1u << ib);
  }
}

The above is untested but you should get the main idea.

unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40
unwind
  • 391,730
  • 64
  • 469
  • 606