modified: bplot.R
[GalaxyCodeBases.git] / c_cpp / readscorr / bitarray.h
blobba4f8cec7c5f49bf2567e65f393cd306342a9ce1
1 // From http://c-faq.com/misc/bitsets.html
2 // See also /usr/include/X11/extensions/xtrapbits.h
3 // Added BITTOGGLE, BITCOPY and BITVALUE without ByteInArray from xtrapbits.h, also change to UPPER case.
4 // by Hu Xuesong
6 #ifndef __GA_BITARRAY_H
7 #define __GA_BITARRAY_H "@(#)bitarray.h 0.1 - 20110428"
9 #include <limits.h> /* for CHAR_BIT */
11 #define BITMASK(b) /* Returns the bit mask of a byte */ \
12 (1 << ((b) % CHAR_BIT))
14 #define BITSLOT(b) ((b) / CHAR_BIT) // Just the index of char[]
16 #define BITSET(a, b) /* Set a specific bit to be True */ \
17 ((a)[BITSLOT(b)] |= BITMASK(b))
19 #define BITCLEAR(a, b) /* Set a specific bit to be False */ \
20 ((a)[BITSLOT(b)] &= ~BITMASK(b))
22 #define BITTOGGLE(a,b) /* Toggle a specific bit */ \
23 ((a)[BITSLOT(b)] ^= BITMASK(b))
25 #define BITTEST(a, b) /* Test to see if a specific bit is True={1,2,4,8} */ \
26 ((a)[BITSLOT(b)] & BITMASK(b))
28 #define BITCOPY(dest,src,bit) /* Copy a specific bit between TWO bit-arrays*/ \
29 BITTEST((src),(bit)) ? BITSET((dest),(bit)) : BITCLEAR((dest),(bit))
31 #define BITVALUE(array,bit) /* Return True=1 or False=0 depending on bit */ \
32 (BITSET((array),(bit)) ? 1 : 0)
34 #define BITNSLOTS(nb) ((nb + CHAR_BIT - 1) / CHAR_BIT) // caltulate the length of char[]
37 (If you don't have <limits.h>, try using 8 for CHAR_BIT.)
39 Here are some usage examples. To declare an ``array'' of 47 bits:
41 char bitarray[BITNSLOTS(47)];
43 To set the 23rd bit:
45 BITSET(bitarray, 23);
47 To test the 35th bit:
49 if(BITTEST(bitarray, 35)) ...
51 To compute the union of two bit arrays and place it in a third array
52 (with all three arrays declared as above):
54 for(i = 0; i < BITNSLOTS(47); i++)
55 array3[i] = array1[i] | array2[i];
57 To compute the intersection, use & instead of |.
59 As a more realistic example, here is a quick implementation of the Sieve
60 of Eratosthenes, for computing prime numbers:
62 #include <stdio.h>
63 #include <string.h>
65 #define MAX 10000
67 int main()
69 char bitarray[BITNSLOTS(MAX)];
70 int i, j;
72 memset(bitarray, 0, BITNSLOTS(MAX));
74 for(i = 2; i < MAX; i++) {
75 if(!BITTEST(bitarray, i)) {
76 printf("%d\n", i);
77 for(j = i + i; j < MAX; j += i)
78 BITSET(bitarray, j);
81 return 0;
84 #endif /* __GA_BITARRAY_H */