Mail Archives: djgpp/1997/10/16/22:46:39
A. Jans-Beken wrote:
>
> In a program i'am writing I have a class like this:
>
> class PROPS {
> unsigned long set_of_32_bits;
> ...
> }
>
> Now I want to have an operator '[]' so I can program:
>
> PROPS flags;
> flags[2] = FALSE;
> flags[4] = flags[31] = TRUE;
> flags[6] = flags[3];
>
> Please note that this is not the famous BITVECT example that can be
> found in many books about c++. I do not want to use a pointer to a bit
> set because the pointer takes up 4 bytes extra and i'am planning to use
> a huge array of PROPS (and related classes).
This doesn't work the way you are asking in C. C has a complete set of
operators designed specifically to work on individual bits of an integer
type. The most common way of handling this is to #define a set of
constants, each with a single bit set, and then use the bitwise
operators to set or unset these flags from your variable.
I posted a quick and dirty example of this yesterday on the newsgroup;
I'd rather not repeat myself over and over so I'll just cover the
basics. For more information, you should ask in a newsgroup like
comp.lang.c or consult any decent C textbook.
The bitwise operators are as follows:
& bitwise AND &= assignment operator
| bitwise OR |= assignment operator
^ bitwise XOR ^= assignment operator
<< bitwise shift left <<= assignment operator
>> bitwise shift right >>= assignment operator
A basic operation set would look like this:
#define FLAG_0 1 /* 0001 */
#define FLAG_1 2 /* 0010 */
#define FLAG_2 4 /* 0100 */
#define FLAG_3 8 /* 1000 */
unsigned long flags;
flags = flags | FLAG_0 /* set bit */
flags = flags & ~FLAG_0 /* unset bit */
flags = flags ^ FLAG_0 /* toggle bit */
if ( flags & FLAG_0 ) /* test bit */
....
I'm sure you can figure out the rest. :)
--
---------------------------------------------------------------------
| John M. Aldrich | "Money is truthful. If a man speaks |
| aka Fighteer I | of his honor, make him pay cash." |
| mailto:fighteer AT cs DOT com | |
| http://www.cs.com/fighteer | - Lazarus Long |
---------------------------------------------------------------------
- Raw text -