From: "Mike Collins" Newsgroups: comp.os.msdos.djgpp Subject: Somebody please explain : Length of bit fields Date: Tue, 21 Dec 1999 23:07:57 -0000 Organization: Customer of Planet Online Lines: 79 Message-ID: <83p1rp$oiu$1@newsg3.svr.pol.co.uk> NNTP-Posting-Host: modem-61.plutonium.dialup.pol.co.uk X-Trace: newsg3.svr.pol.co.uk 945818297 25182 62.136.46.189 (21 Dec 1999 23:18:17 GMT) NNTP-Posting-Date: 21 Dec 1999 23:18:17 GMT X-Complaints-To: abuse AT theplanet DOT net X-Priority: 3 X-MSMail-Priority: Normal X-Newsreader: Microsoft Outlook Express 5.00.2314.1300 X-MimeOLE: Produced By Microsoft MimeOLE V5.00.2314.1300 To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Reply-To: djgpp AT delorie DOT com Folks, I came across an interesting thing: In the program below, I would have expected a structure length of 6 bytes, but in fact, when I compile it and single step it, I read the values for a, b, c, d printed below. Of particular interest is the value of a ( the sizeof the entire structure) = 8. #include struct CATALOG { unsigned unit:8, // 4 bytes category:8, refresh :1; short num; // 2 bytes }; main() { int a, b, c, d, e; struct CATALOG ctg; a = sizeof ctg; b = sizeof(ctg.num); c = sizeof(ctg.unit); d = sizeof(ctg.category); // e = sizeof(ctg.refresh); // DJGPP doesn't like sizeof(a_bit_field); } a: 8 b: 2 c: 4 d: 4 If I move the short in front of the unsigned to change the word boundaries, like this : struct CATALOG { short num; unsigned unit:8, category:8, refresh :1; }; ... I still get exactly the same results. If I now reduce the length of catalog.category to a bit field of 7, and remove the line that reads "d = ... " (because DJGPP doesn't like sizeof(a_bit_field)) I get the results printed below. struct CATALOG { short num; unsigned unit:8, category:7, refresh :1; }; a: 4 b: 2 c: 4 Why does the length of the structure change? The length of all bit fields in a single unsigned integer should always be 4 bytes (sizeof(unsigned) == 4) as long as the total number of bits declared is less than 32. Again, putting the "short num" at the head of the structure or at its tail makes no difference to the results. Another thing that interests me is that sizeof(a_bit_field) compiles ok if the bit field is 8 bits long, but if it is a fraction of a byte, the compile throws up an error. Your learned opinions will be most appreciated. -- Mike Collins PS. If replying by e-mail, please make the obvious correction to my address.