- C Programming Basics
- C Tutorial
- C Program Structure
- C Basic Syntax
- C Data Types
- C Constants
- C Variables
- C Operators
- C Ternary Operator
- C Storage Classes
- C Flow of Control
- C Decision Making
- C if if-else Statement
- C switch Statement
- C Loops
- C for Loop
- C while Loop
- C do-while Loop
- C goto Statement
- C break Statement
- C continue Statement
- C Popular Topics
- C Arrays
- C Strings
- C Pointers
- C Functions
- C Recursion
- C Scope Rules
- C Programming Advance
- C Structures
- C Unions
- C Bit Fields
- C Enumerations
- C Input & Output
- C Typedef
- C Preprocessors
- C Type Casting
- C Recursion
- C Error Handling
- C Linked Lists
- C Stacks
- C Queues
- C Binary Trees
- C Header Files
- C File I/O
- C Variable Arguments
- C Memory Management
- C Command Line Arguments
- C Programming Examples
- C Programming Examples
- C Programming Test
- C Programming Test
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(); if(status.cts) printf("clear to send"); if(status.dsr) 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;
« Previous Tutorial Next Tutorial »
Follow/Like Us on Facebook
Subscribe Us on YouTube