C Implementation of Bitmap
#C#Null#File#INI#Test
In fact, we use each element to represent a 32-bit binary string, so this element can store information about the presence of 32 adjacent numbers, and the array size is reduced to 10,000,000 / 32. For example, for the number 89256, since 89256 mod 32 = 2789 with a remainder of 8, we should set the 8th bit (starting from the least significant bit) of the 32-bit string in a[2789] to 1.
Basic Operations:
[cpp] view plain copy
- #define WORD 32
- #define SHIFT 5 //// Shift 5 bits. Left shift is equivalent to multiplying by 32, right shift is equivalent to integer division by 32.
- #define MASK 0x1F // 31 in hexadecimal
- #define N 10000000
- int bitmap[1 + N / WORD];
- /*
- * Set bit function - uses "|" operator. i & MASK is equivalent to modulo operation.
- * For m mod n, when n is a power of 2, m mod n = m & (n-1).
- */
- void set(int i) {
- bitmap[i >> SHIFT] |= (1 << (i & MASK));
- }
- /* Clear bit operation, uses "&~" operator */
- void clear(int i) {
- bitmap[i >> SHIFT] &= ~(1 << (i & MASK));
- }
- /* Test bit operation, uses "&" operator */
- int test(int i) {
- return bitmap[i >> SHIFT] & (1 << (i & MASK));
- }
Implementing Sorting (No Duplicates):
[cpp] view plain copy
- int main(void) {
- FILE *in = fopen("in.txt", "r");
- FILE *out = fopen("out.txt", "w");
- if (in == NULL || out == NULL) {
- exit(-1);
- }
- int i = 0;
- int m;
- for (i = 0; i < N; i++) {
- clear(i);
- }
- while (!feof(in)) {
- fscanf(in, "%d", &m);
- printf("%d/n", m);
- set(m);
- }
- printf("abnother");
- for (i = 0; i < N; i++) {
- if (test(i)) {
- printf("%d/n", i);
- fprintf(out, "%d/n", i);
- }
- }
- fclose(in);
- fclose(out);
- return EXIT_SUCCESS;
- }