Bitfield packing

Der Herr Hofrat der.herr@mail.hofr.at
Sat Aug 17 11:58:00 GMT 2002


> Hi, 
> 
> I am using gcc for a microcontroller application. I want to use
> bitfields to describe the processor registers, 
> similar to this: 
> 
> typedef union {
> 	IO_BYTE byte; 
> 	struct {
> 		IO_BYTE P30 :1; 
> 		IO_BYTE P31 :1; 
> 		IO_BYTE P32 :1; 
> 		IO_BYTE P33 :1; 
> 		IO_BYTE P34 :1; 
> 		IO_BYTE P35 :1; 
> 		IO_BYTE P36 :1; 
> 		IO_BYTE P37 :1; 
> 	} bit; 
> } PDR2;
> 
> How does gcc handle bitfields like thisone? Above I have defined 8 bits,
> are they distributed on several bytes with some optimization levels?

if you don't use any __attribute__((packed)) on the bitfields the size of
this object will be alligned machin dependant (probably 32bit on a 32bit box)
you can see that by using the __alignof__() (just like sizeof) function to
report allignement - internal ordering I guess is nothing you should ever 
relie on. See the section "storage layout" in the gcc manual for infos on
what may influence your setup (i.e. BITS_PER_UNIT).

If you want to be shure of the bit-positions I guess you must use 
bit-operators and allocate an unsigned char / u8 object.

hofrat



More information about the Gcc-help mailing list