C language: - BIT FIELDS in Structures
· C permits us to use small bit fields to hold data items and thereby to pack several data items in a word or 2 bytes of memory.
· A bit field is a set of adjacent bits whose size can be from 1to16 bits in lengths.
· The name and size of bit fields are declared using a structure.
· The syntax of bit fields is
Struct tag- name
{
data-type name1: bit-lenth;
data-type name2: bit-lenth;
………………………
………………………
data- type nameN: bit-lenth;
}
· The data type is either int or unsigned int or signed int
· The length is the number of bits(one bit for signed int or int).
The rules for bit fields :
1) The first field always starts with the first bit of the word.
2) A bit field cannot overlap integer boundaries.
3) There can be unnamed fields declared with size.
Example:
Unsigned : bit-length
4) There can be unused bits in a word.
5) We cannot take the address of a bit field variable.
6) We cannot use scanf,pointers,arrays to read values into bit fields.
7) Bit fields should be assigned values that are within the range of their size.
Example:
Example:
Struct personal
{
Unsigned sex : 1
Unsigned age : 7
Unsigned m_status : 1
Unsigned children : 3
Unsigned : 4
} emp;
This defines a variable name emp with four bit fields. The range of values each field could have as follows:
Bit field Bit length Range of value
Sex 1 0 or 1
Age 7 0 or 127
M_status 1 0 or 1
Children 3 0 to 7
No comments:
Post a Comment