bit array,use less memory to describe a set of int number,
example:
/**
* use bit string to store int numbers,if char[n] = 1,then n is include,else n is not exclude,
*/
#include <stdio.h>
// set a bit to 1,which indicate that a number is include,
void setbit(char data[], int pos);
// get a bit,1 = include,0 = exclulde,
char getbit(char data[], int pos);
// indicate the position of bit in byte[]
struct bit_of_ints {
int a; // byte's subscript
char b; // position in a single byte,0 - 7,
};
// get position struct by pos,
struct bit_of_ints figure_bit_of_ints(int pos);
int main() {
int length = 100;
// figure byte count
int bytecount = (length >> 3) + (length % 8 == 0 ? 0 : 1);
char data[bytecount];
int i;
// init byte[]
for (i = 0; i < bytecount; i++) {
data[i] = 0;
}
// set bits
for (i = 0; i < length; i++) {
if (i % 10 == 0) {
setbit(data, i);
}
}
// get bits
for (i = 0; i < length; i++) {
if (getbit(data, i) != 0) {
printf("%d,", i);
}
}
printf("\n");
return 0;
}
struct bit_of_ints figure_bit_of_ints(int pos) {
struct bit_of_ints boi;
char b = pos % 8;
boi.a = pos >> 3;
switch (b) {
case 0:
boi.b = 0x80;
break;
case 1:
boi.b = 0x40;
break;
case 2:
boi.b = 0x20;
break;
case 3:
boi.b = 0x10;
break;
case 4:
boi.b = 0x08;
break;
case 5:
boi.b = 0x04;
break;
case 6:
boi.b = 0x02;
break;
case 7:
boi.b = 0x01;
break;
default:
break;
}
return boi;
}
void setbit(char data[], int pos) {
struct bit_of_ints bis = figure_bit_of_ints(pos);
data[bis.a] |= bis.b;
}
char getbit(char data[], int pos) {
struct bit_of_ints bis = figure_bit_of_ints(pos);
return data[bis.a] & bis.b;
}

本文介绍了一种使用位数组来表示整数集合的方法,并提供了完整的C语言实现。通过将每个整数映射到位数组的一个比特位上,可以高效地记录某个整数是否属于该集合。

被折叠的 条评论
为什么被折叠?



