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