C Bit Fields

C has a built-in feature, called a bit-field, that allows you to access a single bit. Bit-fields can be useful for the following reasons:

  • If storage is limited, then you can store several Boolean (true/false) variables in one byte.
  • Certain devices transmit status information encoded into one or more bits within a byte.
  • Certain encryption routines need to access the bits within a byte.

A bit fields must be a member of a structure or union. It defines how long, in bits, the field is to be. Here is the general form of a bit-field definition:

type name : length;

Here, type is the type of the bit-field, and length is the number of bits in the field. The type of a bit-field must be int, signed, or unsigned.

Bit-fields are frequently used when analyzing input from a hardware device. For instance, the status port of a serial communications adapter might return a status byte organized like this:

Bit Meaning when set
0 Change in clear-to-send line
1 Change in data-set-ready
2 Trailing edge detected
3 Change in receive line
4 Clear-to-send
5 Data-set-ready
6 Telephone ringing
7 Received signal

You can represent the information in a status byte using the following bit-field:

struct status_type
   unsigned delta_cts: 1;
   unsigned delta_dsr: 1;
   unsigned tr_edge:   1;
   unsigned delta_rec: 1;
   unsigned cts:       1;
   unsigned dsr:       1;
   unsigned ring:      1;
   unsigned rec_line:  1;
} status;

You might use statements like the ones given below to enable a program to determine when it can send or receive data:

status = get_port_status();
   printf("clear to send");
   printf("data ready");

And to assign a value to a bit-field, simply use the form you would use for any other type of structure element. For example, here this code fragment clears the ring field:

status.ring = 0;

C Online Test

« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook

Subscribe Us on YouTube