代码之家  ›  专栏  ›  技术社区  ›  TypicalBeginner

使用位图跟踪阵列

  •  -3
  • TypicalBeginner  · 技术社区  · 8 年前

    我有一个大小为10的数组

    我想跟踪数组中的可用空间,有人告诉我位图是更好的选择。

    例如,索引2和3为空,我可以在位图中的索引2和3处记录位0

    如何使用默认0位创建大小为10的位图?

    欢迎提供有关位图的有用链接。

    提前感谢

    1 回复  |  直到 8 年前
        1
  •  1
  •   unalignedmemoryaccess    8 年前

    C对“位图”类型没有任何一流的支持;你必须自己实施。它非常简单,只需使用一个无符号整数数组和一些位移位/逻辑运算符。

    类似于:

    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);
      }
    }
    

    以上内容未经测试,但您应该了解主要内容。