Revision: 18 Committed: Mon Jul 18 21:00:21 2011 UTC (8 years ago) by gpertea File size: 2183 byte(s) Log Message: ```added a few more source files, test code ```
Line User Rev File contents
1 gpertea 18 // This class provides a generic bit field implementation for an
2     // arbitrary number of bits. Based on code written by irfan.hamid@gmail.com
3     //
4     // Implementation notes:
5     // // The bit field is implemented as an array of unsigned int that is
6     // allocated at object creation.
7     //
8     // field: The array that represents the bit field itself
9     // bit_count: The total number of bits in the bit field
10
11     #ifndef __GBITFIELD_H__
12     #define __GBITFIELD_H__
13     #include "GBase.h"
14     #define SZ_UINT sizeof(unsigned int)
15
16     class GBitField {
17     protected:
18     unsigned int *field;
19     unsigned int bit_count;
20
21     public:
22     // The constructor takes an int param which gives the number of
23     // bits in this bit field.
24     GBitField (int bc) {
25     bit_count = bc;
26     GMALLOC(field, ceil(bc/SZ_UINT*8));
27     }
28     ~GBitField () {
29     GFREE(field);
30     }
31
32     // This function sets the corresponding bit in the field equal to v
33     // (or 1, if v was not given)
34     // Returns: 0 on success, -1 on error.
35     int set(int bit, int v=1) {
36     // Sanity check
37     if (bit >= bit_count || !field)
38     return -1;
39     // The correct index into the vector will be given by bit/SZ_UNIT. The
40     // index into the correct vector element is given by bit%SZ_UNIT, to
41     // achieve this, simply left shift 0x01 the appropriate number of times.
42     if (v==0) {
43     field[bit/SZ_UINT] &= ~(1 << (bit%(SZ_UINT*8)-1));
44     }
45     else {
46     field[bit/SZ_UINT] |= (1 << (bit%(SZ_UINT*8)-1));
47     }
48     return 0;
49     }
50
51     // This function returns the value of the corresponding bit.
52     // Returns: The value of the bit, if the field is initialized and bit index is
53     // within bounds, -1 otherwise.
54     int get(int bit) {
55     if (bit >= bit_count || !field)
56     return -1;
57     return (field[bit/SZ_UINT] & (0x00000001 << (bit%(SZ_UINT*8)-1)) ? 1 : 0);
58     }
59
60     // This function sets the corresponding bit in the field equal to 0.
61     // Returns: 0 on success, -1 on error.
62     int reset(int bit) {
63     if (bit >= bit_count || !field)
64     return -1;
65     field[bit/SZ_UINT] &= ~(0x00000001 << (bit%(SZ_UINT*8)-1));
66     return 0;
67     }
68     };
69
70
71
72     #endif