Bit Fields
It is possible to specify the fields within a structure in terms of bits. This
can be useful when interfacing with hardware devices, for example, or simply to
store boolean values using one eighth of the memory amount taken up by the
bool type.
Bit fields can either be a non floating-point type
(typically
unsigned int), or an enumeration.
For example, if you want to store the name of a person and two boolean values
in two bits, corresponding to married status and European citizenship you can
use:
struct Id
{
char name[20];
unsigned married: 1; // uses one bit
unsigned europeanCitizen: 1;
} myId;
To set a bit field:
myId.married = 1;
It might also be necessary to define a structure corresponding to a byte for
example, in order to save the data coming from a byte received serially from
another computer. In such a case, if only the last two bits are significant,
a structure can be defined in which the first six bits' meaning is not
specified. Further, a bit-field might take up more than one bit:
struct IdFromByte
{
unsigned: 3; // three bits are used. meaning unspecified
unsigned married: 1;
unsigned europeanCitizen: 1;
unsigned childrenNumber: 3;
};
Example
struct Id
{
char name[20];
unsigned married: 1;
unsigned europeanCitizen: 1;
};
struct IdFromByte // structure takes up a byte
{
unsigned: 3; // three bits are used, the meaning unspecified
unsigned married: 1;
unsigned europeanCitizen: 1;
unsigned childrenNumber: 3; // maximum number stored: 7
};
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
Id myId;
strcpy(myId.name, "Erika");
myId.married = 1;
myId.europeanCitizen = 0;
IdFromByte anIdFromByte;
anIdFromByte.married = 1;
anIdFromByte.europeanCitizen = 1;
anIdFromByte.childrenNumber = 3;
cout << "married: " << anIdFromByte.married << endl;
cout << "europeanCitizen: " << anIdFromByte.europeanCitizen << endl;
cout << "childrenNumber: " << anIdFromByte.childrenNumber << endl;
}
Output
married: 1
europeanCitizen: 1
childrenNumber: 3