Wednesday, June 18, 2008

Bit Fields

About bit fields in C/C++...

A Bit Field allows us to create variable names for individual bits. Allocation is done from RIGHT to LEFT.

struct bit_field
{
unsigned int Firstbit :1;
unsigned int Secondbit :1;
unsigned int Next2bits :2;
unsigned int Last4bits :4;
} bitField;


{[15][14][13][12][11][10][9][8][7][6][5][4][3][2][1][0]}
[0] -- Firstbit
[1] -- Secondbit
[3][2] -- Next2bits
[7][6][5][4] -- Last4bits
[15][14][13][12][11][10][9][8] -- Un Used bits.


If you use just "int" instead of "unsigned int" then the leftmost bit in the bitfield in question will be a sign bit.
It can be used as follows : printf(bitField.Firstbit);

No comments: