7. Bit Fields
|
|
A bit-field is a set of adjacent bits within a single ‘word’. |
|
A union is a variable that may hold objects of different types/sizes in the same memory location. |
|
Example: |
struct {
unsigned int is_keyword : 1;
unsigned int is_extern : 1;
unsigned int is_static : 1;
} flags; |
|
|
– This defines a variable table called flags that contains three 1-bit fields.
– The number after the colons specifies the width in bits.
– Each variables should be declared as unsigned int.
– Fields are assigned left to right on some machines and right to left on others. |
|
Bit fields vs. masks |
struct flag {
unsigned int is _color : 1;
unsigned int has_sound : 1;
unsigned int is _ntsc : 1;
}; |
|
|
CLR=0x1, SND=0x2, NTSC=0x4; |
struct flag f; |
x|=CLR;
x|=SND;
x|=NTSC; |
f.is_color = 1;
f.has_sound = 1;
f.is_ntsc = 1; |
x&=~CLR;
x&=~SND; |
f.is_color = 0;
f.has_sound = 0; |
if (x&CLR || x&NTSC) |
if (f.is_color || f.is_ntsc) |
|
|