TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: RICK BISCHOFF
from: KURT KUZBA
date: 1997-03-23 13:24:00
subject: Bit Fields

RB>   Does anyone know how to declare a variable that holds
RB>   only one bit of information..
RB>   (You know only two values (0 or 1)) ???
rb>......
   You can only do this inside of a struct or a class.
The general syntax for it is: vartype varname:varbits;
How about a quick example?
//_|_|_|   DATEBITS.CPP
//_|_|_|   PUBLIC DOMAIN   by Kurt Kuzba.  (3/23/1997)
#include 
class Dosdate{
public:
   void SetYear(int y)
          {y -= 1970; yr = (y  127) ? 0 : y; }
   void SetMonth(int m){mn = (m  12)  ? 0 : m; }
   void SetDay(int d)  {dy = (d  31)  ? 0 : d; }
   const int GetYear(){return yr + 1970;}
   const int GetDay() {return  dy;}
   const char *GetMonth()
   {
      char *MN[13] = {
         "Nul", "Jan", "Feb", "Mar", "Apr", "May", "Jun",
         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
      return MN[mn];
   }
   //_|_|_|  compiler will likely kick this out of inline.
private:
   unsigned int
      yr : 7,
      mn : 4,
      dy : 5;
};
int main(void)
{
   Dosdate DD;
   DD.SetYear(1997);
   DD.SetMonth(3);
   DD.SetDay(23);
   cout << "Dosdate uses "
        << (8 * sizeof(DD)) << " bits.\n"
        << DD.GetMonth()    << '/'
        << DD.GetDay()      << '/'
        << DD.GetYear()     << '\n'  << flush;
   return 0;
}
> ] Cold pizza is Nature's most perfect food....................
---
---------------
* Origin: *YOPS ]I[* 3.1 GIG * RA/FD/FE RADist * Milwaukee, WI (1:154/750)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.