www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/04/01/00:47:52

From: "John M. Aldrich" <fighteer AT cs DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Help with bits!
Date: Tue, 31 Mar 1998 23:56:17 -0500
Organization: Two pounds of chaos and a pinch of salt.
Lines: 66
Message-ID: <3521C8F1.7567@cs.com>
References: <3521BAF7 DOT AB240651 AT primary DOT net>
NNTP-Posting-Host: ppp225.cs.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

* benz wrote:
> 
> OK, I feel like a newbie, but I can't figure out how to check individual
> bits in a char or int.  I heard something about a bitmask, but I'm not
> sure how to use one.  I want to know this becuase I have a whole bunch
> of vars that will only contain a 1 or a 0 and I figure that it would be
> easier for me to have eight of these in one byte, not in eight.

It's easy.  C features a set of operators called "bitwise operators",
which operate logically on individual bits of an integer variable type. 
The full set of operators is thus:

  Op.    Effect          Example
   &	logical AND	11100111 & 00111111 = 00100111
   |	logical OR      11100111 | 00111111 = 11111111
   ^	logical XOR     11100111 ^ 00111111 = 11011000
   ~	logical NOT     ~11100111           = 00011000
   <<   shift left      11100111 << 2       = 10011100
   >>   shift right	11100111 >> 2       = 00111001 (unsigned)
                                              11111001 (signed)

All of these operators except ~ (NOT) have assignment variants; i.e.,
&=, |=, ^=, <<=, >>=.  The order of precedence for logical operators can
be found in any C text.

The following set of C macros illustrate the use of bitwise operators to
set specific bits of an integer variable:

#define A	  1
#define B	  2
#define C	  4
#define D	  8
#define E	 16
#define F	 32
#define G	 64
#define H	128

#define SET_BIT(bitvector, bit) 	((bitvector) |= (bit))
#define REMOVE_BIT(bitvector, bit)	((bitvector) &= ~(bit))
#define TOGGLE_BIT(bitvector, bit)	((bitvector) ^= (bit))
#define IS_SET(bitvector, bit)		((bitvector) | (bit))

/* code */
    int flag;
    SET_BIT(flag, A);
    SET_BIT(flag, B | D);
    if ( IS_SET(flag, D) )
        printf( "flag D set.\n" );
    REMOVE_BIT(flag, B);
    TOGGLE_BIT(flag, G);


Now that I've given you a complete tutorial, I'll mention that this is
an off-topic subject that would better be discussed in comp.lang.c.  :-)

hth

-- 
John M. Aldrich, aka Fighteer I <fighteer AT cs DOT com>  UIN# 7406319

-----BEGIN GEEK CODE BLOCK-----
Version: 3.1
GCS d- s+:- a-->? C++>$ U@>++$ p>+ L>++ E>++ W++ N++ o+>++ K? w(---)
O- M-- V? PS+ PE Y+ PGP- t+(-) 5- X- R+(++) tv+() b+++ DI++ D++ G>++
e(*)>++++ h!() !r !y+()
------END GEEK CODE BLOCK------

- Raw text -


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