【问题标题】:Keeping track of array using Bit maps使用位图跟踪数组
【发布时间】:2018-03-08 13:04:18
【问题描述】:

我有一个大小为 10 的数组

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

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

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

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

提前致谢

【问题讨论】:

  • 欢迎来到 Stack Overflow。请访问Help Center 并阅读How To Ask
  • 一个整数有多少位?会超过10个吗?每个条目 1 位还不够吗?

标签: c arrays bitmap bitmapdata


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多