位图

相关数据结构
typedef uint64_t BitmapType;

#define BITMAPMAXSIZE 1000 //位图所能容纳的位数

typedef struct Bitmap
{
    uint64_t* data;
    uint64_t capacity;
}Bitmap;
初始化
void BitmapInit(Bitmap* bm, uint64_t capacity)
{
    if(bm == NULL)
    {
        return;
    }
    //当capacity = 100, 2个元素
    //当capacity = 200, 4个元素
    //当capacity = 300, 5个元素
    //当capacity = N, capacity / 64 + 1   => capacity / (sizeof(uint64_t) * 8) + 1
    bm -> capacity = capacity;  
    uint64_t size = capacity / (sizeof(uint64_t) * 8) + 1;//位图对应的数组有几个元素
    bm -> data = (BitmapType*)malloc(sizeof(BitmapType) * size);
}
销毁
void BitmapDestroy(Bitmap* bm)
{
    if(bm == NULL)
    {
        return;
    }
    bm -> capacity = 0;
    free(bm -> data);
    bm -> data = NULL;
}
将某一位设置为1
void GetOffset(uint64_t index, uint64_t* offset, uint64_t* n)
{
    if(offset == NULL || n == NULL)
    {
        return ;
    }
    *n = index / (sizeof(BitmapType) * 8);
    *offset = index % (sizeof(BitmapType) * 8) ;
}

void BitmapSet(Bitmap* bm, uint64_t index)
{
    if(bm == NULL || index >= bm -> capacity)
    {
        return;
    }
    uint64_t n, offset;
    GetOffset(index, &n, &offset);
    bm -> data[n] |= (0x1lu << offset);
}
将某一位设置为0
void BitmapUnSet(Bitmap* bm, uint64_t index)
{
    if(bm == NULL || index >= bm -> capacity)
    {
        return;
    }
    uint64_t offset, n;
    GetOffset(index, &n, &offset);
    bm -> data[n] &= ~(0x1lu << offset);
}
检测某一位是0还是1
int BitmapTest(Bitmap* bm, uint64_t index)
{
    if(bm == NULL)
    {
        return 0;
    }
    uint64_t n, offset;
    GetOffset(index, &n, &offset);
    uint64_t ret = bm -> data[n] & (0x1lu << offset);
    if(ret == 0)
    {
        return 0;
    }
    return 1;
}
将位图每一位都设置为1
void BitmapFill(Bitmap* bm)
{
    if(bm == NULL)
    {
        return;
    }
    uint64_t size = bm -> capacity / (sizeof(BitmapType) * 8) + 1;
    memset(bm -> data, 0xff, sizeof(uint64_t) * size);
}
将位图清零
void BitmapClean(Bitmap* bm)
{
    if(bm == NULL)
    {
        return;
    }
    uint64_t size = bm -> capacity / (sizeof(BitmapType) * 8) + 1;
    memset(bm -> data, 0x00, sizeof(uint64_t) * size);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值