位图,用位运算实现

一个真正的“位“图,想实现一个内存池研究了一下。

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DECLARE_BITMAP(name) uint64_t name[8]

struct memory_pool
{
	DECLARE_BITMAP(bitmap);
};

// 1000B => 8H
#define FIRST1_64 0x8000000000000000

void setbitmap(uint64_t* bitmap, uint64_t index)
{

	uint64_t visit = FIRST1_64;

	visit >>= index;

	bitmap[index / 64] |= visit;
}

int findempty(uint64_t* bitmap)
{
	uint64_t map;
	uint64_t visit = FIRST1_64;
	for (int i = 0; i < 8; ++i)
	{

		map = bitmap[i];

		for (int j = 0; j < 64; ++j)
		{
			if ((map & visit)) {
				return j + i * 64;
			}
			visit >>= 1;
		}
		visit = FIRST1_64;
	}
	return -1;
}

void clearbit(uint64_t* bitmap, int index)
{
	uint64_t clear = FIRST1_64;
	clear >>= index;
	bitmap[index / 64] ^= clear;
}

int main() {
	struct memory_pool* pool = (struct memory_pool*)malloc(sizeof(struct memory_pool));
	memset(pool->bitmap, 0, 8 * sizeof(uint64_t));
	setbitmap(pool->bitmap, 127);
	setbitmap(pool->bitmap, 64);
	printf("%s:%016lx\n", "0x", pool->bitmap[1]);
	clearbit(pool->bitmap, 64);
	printf("%s:%016lx\n", "after clear: 0x", pool->bitmap[1]);
	int index;
	if (-1 != (index = findempty(pool->bitmap))) {
		printf("index: %d\n", index);
	} else {
		printf("no found\n");
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值