Tuesday, June 12, 2007

Real use of BitFields

Bit-Fields


C/C++ has a built-in feature called a bit-field
that allows you to access a single bit. Bit-fields can be useful for a number of reasons,
such as:
1. If storage is limited, you can store several Boolean (true/false) variables in
one byte.
2. Certain devices transmit status information encoded into one or more bits
within a byte.
3.Certain encryption routines need to access the bits within a byte.


To access individual bits, C/C++ uses a method based on the structure.
The general form of a bit-field definition is

struct struct-type-name {
type name1 : length;
type name2 : length;
..
.
type nameN : length;
} variable_list;

Here, type is the type of the bit-field and length is the number of bits in the field.
A bit-field must be declared as an integral or enumeration type. Bit-fields of length
1 should be declared as unsigned, because a single bit cannot have a sign.
Bit-fields are frequently used when analyzing input from a hardware device.
For example, 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 a routine similar to that shown here to enable a program to determine
when it can send or receive data.


status = get_port_status();
if(status.cts) printf("clear to send");
if(status.dsr) printf("data ready");


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

status.ring = 0;

Labels:

0 Comments:

Post a Comment

<< Home