This article includes bitfield structure
examples.
Please, read it : BITFIELDS
About structure bit1
struct bitfield1
{
unsigned int a:6;
unsigned int b:6;
unsigned int c:6;
char d:8;
} bit1;
bit1.a=5;
bit1.b=14;
bit1.c=6;
bit1.d=9;
We have: size of unsigned int a:6+ size of unsigned int b:6 <16 <size of unsigned int a:6+ size of unsigned int b:6 +size of unsigned int c:6
So a and b will be packed together in the space of an integer (space of 16 bits long),c will be packed alone at a space of 16 bits and d will be packed alone at a space of 16 bits. bit1 is 6 bytes long and it will be :
0000 001110 000101 = 00000011 10000101 =
0x03 0x85
( 14=0x0E=b1110)
The low byte is saved first.
The C code The result
About structure bit3
struct bitfield3
{
unsigned int a:5;
unsigned int b:5;
unsigned int c:5;
char d:5;
} bit3;
bit3.a=5;
bit3.b=14;
bit3.c=6;
bit3.d=9;
We have: size of unsigned int a:5+ size of unsigned int b:5 +size of unsigned int c:5 <16
So, a b and c are packed together in a space of 16 bits , bit3 is 4 bytes long and it will be:
0 00110 01110 00101 = 00011001 11000101 = 0x19 0xc5
bit2 structure is obvius.
Bitfields are useful when memory economy is needed.
|