help regarding Struct in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gunner666
    New Member
    • Feb 2008
    • 3

    help regarding Struct in C

    Hi ,i want to know wat the : stands for, or does to the program here below

    typedef struct ref
    {
    unsigned int en:1;
    unsigned int sm:4;
    unsigned int g:8;
    unsigned int gate:16;
    }
    i want to know what does
    en:1 really mean,
    is it like assignin the variable en wid 1 ,or is it somethin else
    plzzzzz reply
  • gpraghuram
    Recognized Expert Top Contributor
    • Mar 2007
    • 1275

    #2
    Originally posted by gunner666
    Hi ,i want to know wat the : stands for, or does to the program here below

    typedef struct ref
    {
    unsigned int en:1;
    unsigned int sm:4;
    unsigned int g:8;
    unsigned int gate:16;
    }
    i want to know what does
    en:1 really mean,
    is it like assignin the variable en wid 1 ,or is it somethin else
    plzzzzz reply
    It is specifying how many bits you are going to use for storing the value.go through this link to get a good idea abt this

    Raghuram

    Comment

    • krishnabhargav
      New Member
      • Feb 2008
      • 24

      #3
      Originally posted by gunner666
      Hi ,i want to know wat the : stands for, or does to the program here below

      typedef struct ref
      {
      unsigned int en:1;
      unsigned int sm:4;
      unsigned int g:8;
      unsigned int gate:16;
      }
      i want to know what does
      en:1 really mean,
      is it like assignin the variable en wid 1 ,or is it somethin else
      plzzzzz reply
      Those are called Bit Fields...

      en is 1 bit, sm is 4 bits and g is 8 bits while gate is 16 bits

      refer : http://www.informit.co m/guides/content.aspx?g= cplusplus&seqNu m=131

      Comment

      • krishnabhargav
        New Member
        • Feb 2008
        • 24

        #4
        Simple example to illustrate bitfields

        Code:
        #include<iostream>
        
        using namespace std;
        
        typedef struct ref
        {
          unsigned int i:4;
          unsigned int j:2;
        };
        
        int main()
        {
           ref r1;
           cout<<sizeof(r1)<<endl;
           r1.j = 3; //since r1 is 2 bits, max value is "11"(binary) or 3
           cout<<"Value of r1.j(2 bits)"<<r1.j<<endl;
           r1.j = 8; //100 in binary, cannot set 100, instead sets 00 to j's bits
           cout<<"Value of r1.j(2 bits)"<<r1.j<<endl;
        }

        Comment

        • weaknessforcats
          Recognized Expert Expert
          • Mar 2007
          • 9214

          #5
          You are using C++ where bit fields are supported as a deprecated feature only to compile relic C code. You are not supposed to use bit fields in new C++ code.

          Use a bitset<>:
          [code=cpp]
          bitset<32> bits; //32 bits
          [/code]

          Comment

          Working...