Tuesday, 14 April 2015

Bit Fields in C Language

Bit Fields allow the packing of data in a structure or a Union with specified number of bits. This is especially useful when memory or data storage is at a premium or you have data with sizes different from normal datatypes

Example:
IP header can be declared as follows

typedef struct
{
      unsigned Vers                              : 4  ;/* Version number.*/
      unsigned IHL                               : 4  ;/* ethernet Header Length*/
      unsigned TOS                             : 8  ;/* Type of Service.*/
      unsigned TotalLength                  : 16 ;/* Total Length is the length of the datagram.*/
      unsigned Identification                 : 16 ;/* identifying fragments of a datagram.*/
      unsigned Flags                            : 3  ;/* Control Flags (Bit0:res,Bit1:1 = Don't Fragment,Bit2:0 = Last Fragment)*/
      unsigned FragmentOffset             : 13 ;/* Indicates where in the datagram this fragment belongs */
      unsigned TimeToLive                  : 8  ;/* Time to Live */
      unsigned Protocol                       : 8  ;/* Indicates the next level protocol used*/
      unsigned HeaderChecksum         : 16 ;/* checksum on the header only*/
      unsigned SourceAddress            : 32 ;/* Source address*/
      unsigned DestinationAddress      : 32 ;/* Destination address*/
} S_IPv4Header;


the above code will create a structure IPv4Header  which will contain elements
ver                             whose size is 4  bits,
IHL                           whose size is 4  bits,
TOS                          whose size is 8  bits,
TotalLength               whose size is 16 bits,
Identification              whose size is 16 bits,
Flags                         whose size is 3  bits,
Flags                         whose size is 3  bits,
FragmentOffset          whose size is 13 bits,
TimeToLive               whose size is 8  bits,
Protocol                    whose size is 8  bits,
HeaderChecksum      whose size is 16 bits,
SourceAddress          whose size is 32 bits,
DestinationAddress    whose size is 32 bits,

No comments:

Post a Comment