www.digitalmars.com         C & C++   DMDScript  

c++ - I've got a struct with a 12 bit variable and four 1 bit variables,

reply SL <shadowlord13 gmail.com> writes:
#pragma pack(1)
struct pvlist {
     Uword polygon_id : 12;
     Uchar vtxflag_0  : 1;
     Uchar vtxflag_1  : 1;
     Uchar vtxflag_2  : 1;
     Uchar vtxflag_3  : 1;
};
#pragma pack()

The total number of bits there is 16, of course, so it should fit in two 
bytes. However, DMC is making it 3 bytes in size. (If I omit the pragma 
pack stuff, it makes it 4 bytes instead)

I tried changing 'Uword polygon_id : 12' to 'Uchar polygon_id : 12' to 
see if that worked, but it didn't. The compiler complained that "12 
exceeds maximum bit field width of 8 bits."

Rearranging the variables in the struct doesn't make it smaller either.

Oddly, if I omit the type from polygon_id's declaration entirely, the 
struct becomes 5 bytes long. I wouldn't even have expected that to 
compile, heh.

Is this a compiler bug?

The reason I'm asking is because there's some asm code which depends on 
this being 2 bytes in size. If this isn't a compiler bug, I'll "fix" the 
code of course, but it seems to me that DMC is wasting a byte. Or 
possibly I shouldn't be using pragma pack(1), if there's some way to 
tell it not to try to align anything in the struct on any boundaries at 
all (if that's the problem).

-SL
Apr 24 2005
parent reply Bertel Brander <bertel post4.tele.dk> writes:
SL wrote:
 #pragma pack(1)
 struct pvlist {
     Uword polygon_id : 12;
     Uchar vtxflag_0  : 1;
     Uchar vtxflag_1  : 1;
     Uchar vtxflag_2  : 1;
     Uchar vtxflag_3  : 1;
 };
 #pragma pack()
 
 The total number of bits there is 16, of course, so it should fit in two 
 bytes. However, DMC is making it 3 bytes in size. (If I omit the pragma 
 pack stuff, it makes it 4 bytes instead)
This one print 2: #include <iostream> #pragma pack(1) struct pvlist { unsigned short polygon_id : 12; unsigned short vtxflag_0 : 1; unsigned short vtxflag_1 : 1; unsigned short vtxflag_2 : 1; unsigned short vtxflag_3 : 1; }; #pragma pack() int main() { std::cout << sizeof(pvlist) << std::endl; }
Apr 24 2005
parent SL <shadowlord13 gmail.com> writes:
Bertel Brander wrote:
 This one print 2:
 
[An hour or so of testing later] Ah ha - the problem is that DMC doesn't like how I mixed Uword (unsigned short) with Uchar (unsigned char) in the struct. If all of the variables in the struct are Uword it comes out to 2 bytes. I'm kinda wishing DMC had printed a warning that mixing types there is bad. Thanks for the help.
Apr 24 2005