Saturday, 18 May 2013

Bit feilds in c;how to assign an single bit to an variable in c

C offers the capability to define the width of a variable, but only when the variable
is in a structure called a bit field. For example, you could rewrite the definition of Status
as follows:






struct {
unsigned int bIsValid:1;
unsigned int bIsFullSize:1;
unsigned int bIsColor:1;
unsigned int bIsOpen:1;
unsigned int bIsSquare:1;
unsigned int bIsSoft:1;
unsigned int bIsLong:1;
unsigned int bIsWide:1;
unsigned int bIsBoxed:1;
unsigned int bIsWindowed:1;
} Status;



The :1 that appears after each variable’s name tells the compiler to allocate one
bit to the variable. Thus, the variable can hold only a 0 or a 1. This is exactly what is
needed, however, because the variables are TRUE/FALSE variables. The structure is
only two bytes long.



A bit field can hold more than a single bit. For example, it can hold a definition
of a structure member, such as
unsigned int nThreeBits:3;
In this example, nThreeBits can hold any value from 0 to 7.

No comments:

Post a Comment