Mail Archives: djgpp/1998/04/15/10:38:49
Sergio Vale e Pace writes:
> I'm trying to make a struct to work something like this:
>
> defined_struct data;
> data=8;
> data.bit0=1; // data=9
> data.bit2=1; //data=13
Try something like:
#include <stdio.h>
typedef union STUFF
{
int all;
struct {
int bit0 : 1;
int bit1 : 1;
} parts;
} STUFF;
int main()
{
STUFF t;
t.all = 8;
printf("%d\n", t.all);
t.parts.bit0 = 1;
printf("%d\n", t.all);
t.parts.bit1 = 1;
printf("%d\n", t.all);
return 0;
}
I'm not sure how reliable the ordering of these bitfield variables
will be across different compilers and endian formats, though. My
personal tendency is to avoid such explicit bitfields, and do any
binary packing myself with the C logical operators, eg. "val |= 1"
to set a bit and "val &= ~1" to clear it. That way you always know
exactly how the data is ordered, plus your code will be portable
to pre-ANSI compilers that don't support packed bitfields.
Shawn Hargreaves.
- Raw text -