User manual
mikroC PRO for dsPIC
MikroElektronika
221
Bit Fields
Bit elds are specied numbers of bits that may or may not have an associated identier. Bit elds offer a way of
subdividing structures into named parts of user-dened sizes.
Structures and unions can contain bit elds that can be up to 16 bits.
You cannot take the address of a bit eld.
Note: If you need to handle specic bits of 8-bit variables (char and unsigned short) or registers, you don’t
need to declare bit elds.
Much more elegant solution is to use the mikroC PRO for dsPIC30/33 and PIC24’s intrinsic ability for
individual bit access — see Accessing Individual Bits for more information.
Bit Fields Declaration
Bit elds can be declared only in structures and unions. Declare a structure normally and assign individual elds like
this (elds need to be unsigned):
struct tag {
unsigned biteld-declarator-list;
}
Here, tag is an optional name of the structure; biteld-declarator-list is a list of bit elds. Each component
identifer requires a colon and its width in bits to be explicitly specied. Total width of all components cannot exceed two
bytes (16 bits).
As an object, bit elds structure takes two bytes. Individual elds are packed within two bytes from right to left. In
biteld-declarator-list, you can omit identier(s) to create an articial “padding”, thus skipping irrelevant bits.
For example, if there is a need to manipulate only bits 2–4 of a register as one block, create a structure like this:
struct {
unsigned : 2, // Skip bits 0 and 1, no identier here
mybits : 3; // Relevant bits 2, 3 and 4
// Bits 5, 6 and 7 are implicitly left out
} myreg;
Here is an example:
typedef struct {
lo_nibble : 4;
hi_nibble : 4;
high_byte : 8;} myunsigned;
which declares the structured type myunsigned containing three components: lo_nibble (bits 3..0), hi_nibble
(bits 7..4) and high_byte (bits 15..8).