delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/10/16/22:46:39

From: "John M. Aldrich" <fighteer AT cs DOT com>
Newsgroups: comp.lang.c++,comp.os.msdos.djgpp
Subject: Re: How to program a set of bits?
Date: Thu, 16 Oct 1997 18:59:39 +0000
Organization: Two pounds of chaos and a pinch of salt
Lines: 64
Message-ID: <3446641B.1D8A@cs.com>
References: <34462916 DOT 7762 AT oce DOT nl>
Reply-To: fighteer AT cs DOT com
NNTP-Posting-Host: ppp243.cs.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019