linux 学习之位图(bitmap)数据结构

bitmap

可以高效地表示大量的布尔值,并且在许多情况下可以提供快速的位操作。

1 定义

enum device_state{
	DOWN,
	DOEN_DONE,
	MAILBOX_READY,
	MAILBOX_PENDING,

    STATE_BUILD
};
 DECLARE_BITMAP(state,STATE_BUILD)

相当于=》u32 state[BITS_TO_LONGS(4)]

BITS_TO_LONGS(bits) 计算bits 中有多少个 8 字节(32位)元素;

2 函数

set_bit
clear_bit

// 设置指定位置的位值为1
BITMAP_SIZE = 32 //64
void setBit(bool bitmap[], int pos) {
    int index = pos / BITMAP_SIZE;
    int offset = pos % BITMAP_SIZE;
    bitmap[index] |= (1 << offset);
}

bool getBit(bool bitmap[], int pos) {
    int index = pos / BITMAP_SIZE;
    int offset = pos % BITMAP_SIZE;
    return (bitmap[index] >> offset) & 1;
}
void clearBit(bool bitmap[], int pos) {
    int index = pos / BITMAP_SIZE;
    int offset = pos % BITMAP_SIZE;
    bitmap[index] &= ~(1UL << index);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值