Bitwise logic operations are used to implement bitwise vectors. These operations are used to set, clear, and detect bitwise vectors.
The Code is as follows:
private const int bitsPerWord = 32;private const int shift = 5;private const int mask = 0x1F;private const int n = 10000000;private static readonly int[] a = new int[1 + n / bitSperWord];void set(int i){ a[i >> shift] |= (1 << (i & mask));}void clr(int i){ a[i >> shift] &= ~(1 << (i & mask));}int test(int i){ return a[i >> shift] & (1 << (i & mask));}
The function we implement is to specify an integer (32-bit) array, input a parameter I, set the I bit of the array to 1, or clear the I bit, or the I-bit value.
This Code uses too many bit logic operations, and is not easy to understand.
I> shift
In fact, I is divided by 32, that is, 2 ^ 5. The purpose is to find out where I should be in the array.
1 <(I & mask)
I & mask first calculates the number of digits that should be moved to the left, and then moves 1 to the left. The rest is the element in the array or the operation, or the operation.
In fact, we can better understand these terms.
void set(int i){ a[i / 32] |= (1 << (i % 32));}void clr(int i){ a[i / 32] &= ~(1 << (i % 32));}int test(int i){ return a[i / 32] & (1 << (i % 32));}
Bit vectors have good performance and memory advantages in some specific massive data processing applications (such as searching and sorting.