如果我来得不是太晚的话this http://www.mathcs.emory.edu/%7Echeung/Courses/255/Syllabus/1-C-intro/bit-array.html页面给出了很棒的解释和示例。
一个数组int
可以用来处理数组bits
。假设大小为int
to be 4 bytes
,当我们谈论一个int
,我们正在处理32 bits
。说我们有int A[10]
,意味着我们正在努力10*4*8 = 320 bits
如下图所示:(数组的每个元素有4个大块,每个块代表一个byte
每个较小的块代表一个bit
)
因此,要设置k
数组中的第 th 位A
:
// NOTE: if using "uint8_t A[]" instead of "int A[]" then divide by 8, not 32
void SetBit( int A[], int k )
{
int i = k/32; //gives the corresponding index in the array A
int pos = k%32; //gives the corresponding bit position in A[i]
unsigned int flag = 1; // flag = 0000.....00001
flag = flag << pos; // flag = 0000...010...000 (shifted k positions)
A[i] = A[i] | flag; // Set the bit at the k-th position in A[i]
}
或缩短版本
void SetBit( int A[], int k )
{
A[k/32] |= 1 << (k%32); // Set the bit at the k-th position in A[i]
}
类似于清除k
th bit:
void ClearBit( int A[], int k )
{
A[k/32] &= ~(1 << (k%32));
}
并测试是否k
th bit:
int TestBit( int A[], int k )
{
return ( (A[k/32] & (1 << (k%32) )) != 0 ) ;
}
如上所述,这些操作也可以写成宏:
// Due order of operation wrap 'k' in parentheses in case it
// is passed as an equation, e.g. i + 1, otherwise the first
// part evaluates to "A[i + (1/32)]" not "A[(i + 1)/32]"
#define SetBit(A,k) ( A[(k)/32] |= (1 << ((k)%32)) )
#define ClearBit(A,k) ( A[(k)/32] &= ~(1 << ((k)%32)) )
#define TestBit(A,k) ( A[(k)/32] & (1 << ((k)%32)) )