Page 123 - Programming Microcontrollers in C
P. 123
108 Chapter 2 Advanced C Topics
same time, a union that contains these several variables will allow
the programmer to store each in the same memory location.
Bitfields
The concepts of bit fields fall loosely under structures. The first
built-in operations that allow bit manipulations from C involve an
enum. Consider the following enum:
enum {PB1=1,PB2=2,OUT1=4,OUT2=8};
int PORTA;
Notice that the different elements of the enum are each powers of 2.
We can then use an expression like
PORTA |= PB1 | PB2;
to turn on bits corresponding to PB1 and PB2 in the integer PORTA.
Or, these corresponding bits might be turned off in PORTA by
PORTA &= ~(PB1 | PB2);
Tests can be executed like
if(PORTA & (PB1 | PB2) == 0)
Here the argument of the if call will be TRUE if both bits corre
sponding to PB1 and PB2 are turned off in PORTA.
These manipulations are not really special bit manipulations. What
is seen here is merely creation of bit-like operations using normal C.
C does support bit fields. Bit fields are created in the form of a
struct. The following struct defines several bit fields:
struct
{
unsigned int PB1 : 1;
unsigned int PB2 : 1;
unsigned int OUT1: 1;
unsigned int OUT2: 1;
unsigned int ALL : 4;
} FLAGS;
This struct consists of several bit fields. The colon that fol
lows the field name designates the bit field whose size is the number