位图是array of bits。它是如何在C中实现的?
答案 0 :(得分:44)
我假设您正在询问如何在C中实现位图(或位数组)。令人惊讶的是,维基百科上的Bit_array条目描述了这个概念,但实际上并没有展示如何实现基本操作,所以这里。
简而言之,创建一个你最喜欢的无符号类型的数组,并做正确的算术来决定如何设置/清除它中的位。
#include <limits.h> /* for CHAR_BIT */
#include <stdint.h> /* for uint32_t */
typedef uint32_t word_t;
enum { BITS_PER_WORD = sizeof(word_t) * CHAR_BIT };
#define WORD_OFFSET(b) ((b) / BITS_PER_WORD)
#define BIT_OFFSET(b) ((b) % BITS_PER_WORD)
void set_bit(word_t *words, int n) {
words[WORD_OFFSET(n)] |= (1 << BIT_OFFSET(n));
}
void clear_bit(word_t *words, int n) {
words[WORD_OFFSET(n)] &= ~(1 << BIT_OFFSET(n));
}
int get_bit(word_t *words, int n) {
word_t bit = words[WORD_OFFSET(n)] & (1 << BIT_OFFSET(n));
return bit != 0;
}
答案 1 :(得分:1)
您可以使用“位字段”。
$ cat src/bitmap.c
#include <stdio.h>
#define BITS 4
struct BITMAP {
unsigned value : 1;
} bit[BITS];
int main(){
bit[0].value = 0;
bit[1].value = 1;
// implicit truncation from 'int' to bit-field changes value from 2 to 0 [-Wbit/field-constant-conversion]
bit[2].value = 2;
bit[3].value = 3;
int i;
for ( i=0; i < BITS ; i++){
printf("Value of bit %i is %u\n", i, bit[i].value);
}
}
结果
$ gcc src/bitmap.c -lm -o bitmap && ./bitmap
src/bitmap.c: In function ‘main’:
src/bitmap.c:14:24: warning: unsigned conversion from ‘int’ to ‘unsigned char:1’ changes value from ‘2’ to ‘0’ [-Woverflow]
14 | bit[2].value = 2;
| ^
src/bitmap.c:15:24: warning: unsigned conversion from ‘int’ to ‘unsigned char:1’ changes value from ‘3’ to ‘1’ [-Woverflow]
15 | bit[3].value = 3;
| ^
Value of bit 0 is 0
Value of bit 1 is 1
Value of bit 2 is 0
Value of bit 3 is 1