0

Possible Duplicate:
What does 'unsigned temp:3' means
what does this mean in c int a:16;?

I came across this struct in some C++ code I'm working on. Can someone explain to me what the colon operator is doing and why one would use it?

struct MYMSG
{
    unsigned short  src : 4;
    unsigned short  dst : 11;
    unsigned short  tx    : 1;
};
Community
  • 1
  • 1
bporter
  • 4,467
  • 2
  • 19
  • 29
  • Number of bits to be allocated. – cppcoder Dec 28 '11 at 16:10
  • So, of the 16 bits in memory, the src field would only use the 4 LSBs? Or it only allocates 4 bits? – bporter Dec 28 '11 at 16:12
  • @bporter Yes src will use only 4 bits, although it may not be the 4 LSB's. The layout the compiler uses varies by implementation, there is no standard. – shf301 Dec 28 '11 at 16:15
  • 1
    It would have been much easier to close as dupe if there was anyway of searching for ":" - I tried for 5mins and gave up – Martin Beckett Dec 28 '11 at 16:52
  • @Martin - I agree. I wouldn't have asked the question in the first place had I been able to search for it. "temp:3" and "a:16" weren't the first search terms to come to mind. :) Anyway, I'm very grateful for the help I received. Thanks! – bporter Dec 28 '11 at 17:00
  • @bporter - not your fault, in fact it would have been quicker to write the answer than find the dupe. SO has a problem with searching, especially for c/c++ – Martin Beckett Dec 28 '11 at 17:07

1 Answers1

1

As commented above, it's the number of bits to be used for each field.

struct MYMSG
{
    unsigned short  src : 4;   // allows values 0 - 15
    unsigned short  dst : 11;  // allows values 0 - 2047
    unsigned short  tx    : 1; // allows values 0 - 1
};

This also has the effect of packing the structure if alignment is turned off. If this structure is not padded, then a call to sizeof() will return 2 (on an 8-bit/byte architecture).

In this case, a single unsigned short is allocated, and the bit fields are divided up within that value. Setting a value outside the range of one of the fields (such as 16 for src) will cause an overflow of that particular field, but will not alter the values of any other fields (the value of dst will not change).

Take a slightly more obtuse example:

struct T
{
   unsigned long val : 4
};

This still allocates a full unsigned long (32bit on most architectures), but only allows for setting of the first 4 bits giving valid values of 0-15.

Chad
  • 18,706
  • 4
  • 46
  • 63