C Bit Fields
A bit-field in C is a special kind of struct member that allows us to define members bit by bit, specifying the number of bits they occupy.
If a program's structure contains multiple on/off variables, that is, variables whose values are TRUE/FALSE, as follows:
struct
{
unsigned int widthValidated;
unsigned int heightValidated;
} status;
Such a structure requires 8 bytes of memory, but in fact we only store 0 or 1 in each variable.
In this case, C provides a way to make better use of memory: when using such variables inside a structure, you can define the width of a variable, telling the compiler that you will only use those bits.
For example, the structure above can be rewritten as:
struct
{
unsigned int widthValidated : 1;
unsigned int heightValidated : 1;
} status;
Now, the status variable occupies only 4 bytes of memory, but only 2 bits are used to store the value.
If 32 variables with a width of 1 bit are used, the status structure still occupies only 4 bytes; but once 33 variables are used, the 33rd bit will be allocated to the next memory unit, and the whole structure begins to occupy 8 bytes.
Let us look at the following example to understand this concept:
Example
#include
#include
/* Define a simple structure */
struct
{
unsigned
int
widthValidated
;
unsigned
int
heightValidated
;
}
status1
;
/* Define a bit-field structure */
struct
{
unsigned
int
widthValidated
:
1
;
unsigned
int
heightValidated
:
1
;
}
status2
;
int
main
(
)
{
printf
(
"Memory size occupied by status1 : %zu\n"
,
sizeof
(
status1
)
)
;
printf
(
"Memory size occupied by status2 : %zu\n"
,
sizeof
(
status2
)
)
;
return
0
;
}
When the code above is compiled and executed, it produces the following result:
Memory size occupied by status1 : 8
Memory size occupied by status2 : 4
The following table summarizes the characteristics and usage of bit-fields:
| Feature | Description |
|---|---|
| Width Specification | When defining a bit-field, you can specify the bit-field width of a member, that is, the number of bits the member occupies. |
| Width Limit | The width of a bit-field cannot exceed the size of its data type, because the bit-field must fit the integer type used. |
| Data Type | In standard C it should be int, unsigned int, signed int and other integer types; using other types (such as enums) depends on the compiler implementation and is less portable. |
| Combination | Bit-fields can be used alone or combined with other ordinary members to form a structure. |
| Access Method | Through the dot operator (.) or the pointer's arrow operator (->), accessed in the same way as ordinary struct members. |
Bit-field Declaration
Some information does not need to occupy a whole byte when stored, but only a few or one binary bit. For example, when storing an on/off value, there are only two states, 0 and 1, so a single bit is enough. To save storage space and simplify processing, C provides another data structure called a "bit-field" or "bit segment".
A so-called "bit-field" divides the bits of a byte into several different regions and specifies the number of bits in each region. Each field has a field name, allowing operations by field name in the program. In this way, several different objects can be represented by the bit-fields of a single byte.
A typical example: use 1 binary bit to store an on/off value, which has only two states, 0 and 1.
Reading external file formats - it can read non-standard file formats, such as 9-bit integers.
Definition of Bit-fields and Declaration of Bit-field Variables
A bit-field definition is similar to a structure definition, with the form:
struct 位域结构名
{
位域列表
};
The form of the bit-field list is:
type [member_name] : width ;
The following is a description of the variable elements in a bit-field:
| Element | Description |
|---|---|
| type | It can only be one of three types: int (integer), unsigned int (unsigned integer), or signed int (signed integer), which determine how the bit-field value is interpreted. |
| member_name | The name of the bit-field. |
| width | The number of bits in the bit-field. The width must be less than or equal to the bit width of the specified type. |
A variable with a predefined width is called abit-field. A bit-field can store more than 1 bit; for example, if you need a variable to store values from 0 to 7, you can define a bit-field with a width of 3 bits, as follows:
struct
{
unsigned
int
age
:
3
;
}
Age
;
The structure definition above instructs the C compiler that the age variable will use only 3 bits to store this value.
If the assigned value exceeds the range that 3 bits can represent, the excess part will beTruncate the(see Example 2 below).
struct
bs
{
int
a
:
8
;
int
b
:
2
;
int
c
:
6
;
}
data
;
The code above defines a structure named struct bs , data is a struct variable of bs, occupying four bytes in total.
For bit-fields, their width cannot exceed the size of their data type; the size of an int is usually 4 bytes (32 bits).
When adjacent bit-field members have the same type, if the sum of their bit widths does not exceed the size of the type, the later members are stored immediately after the previous one until there is no more room.
Let us look at another example:
span style="color: #993333;">struct packed_struct
{
unsigned
int
f1
:
1
;
unsigned
int
f2
:
1
;
unsigned
int
f3
:
1
;
unsigned
int
f4
:
1
;
unsigned
int
type
:
4
;
unsigned
int
my_int
:
9
;
}
pack
;
The code above defines a structure named packed_struct containing six member variables, and pack is a struct variable of packed_struct.
Here, packed_struct contains 6 members: four 1-bit identifiers f1..f4, a 4-bit type, and a 9-bit my_int.
Let us look at the following example:
Example 1
#include
struct
packed_struct
{
unsigned
int
f1
:
1
;
// 1-bit bit-field
unsigned
int
f2
:
1
;
// 1-bit bit-field
unsigned
int
f3
:
1
;
// 1-bit bit-field
unsigned
int
f4
:
1
;
// 1-bit bit-field
unsigned
int
type
:
4
;
// 4-bit bit-field
unsigned
int
my_int
:
9
;
// 9-bit bit-field
}
;
int
main
(
)
{
struct
packed_struct pack
;
pack.
f1
=
1
;
pack.
f2
=
0
;
pack.
f3
=
1
;
pack.
f4
=
0
;
pack.
type
=
7
;
pack.
my_int
=
255
;
printf
(
"f1: %u\n"
,
pack.
f1
)
;
printf
(
"f2: %u\n"
,
pack.
f2
)
;
printf
(
"f3: %u\n"
,
pack.
f3
)
;
printf
(
"f4: %u\n"
,
pack.
f4
)
;
printf
(
"type: %u\n"
,
pack.
type
)
;
printf
(
"my_int: %u\n"
,
pack.
my_int
)
;
return
0
;
}
The example above defines a structure named packed_struct containing multiple bit-field members.
In the main function, a struct variable pack of type packed_struct is created, and each bit-field member is assigned a value.
Then printf statements are used to print the value of each bit-field member.
The output is:
f1: 1
f2: 0
f3: 1
f4: 0
type: 7
my_int: 255
Example 2
#include
#include
struct
{
unsigned
int
age
:
3
;
}
Age
;
int
main
(
)
{
Age.
age
=
4
;
printf
(
"Sizeof( Age ) : %zu\n"
,
sizeof
(
Age
)
)
;
printf
(
"Age.age : %d\n"
,
Age.
age
)
;
Age.
age
=
7
;
printf
(
"Age.age : %d\n"
,
Age.
age
)
;
Age.
age
=
8
;
// The binary representation 1000 has four bits, exceeding
printf
(
"Age.age : %d\n"
,
Age.
age
)
;
return
0
;
}
The code above will produce a truncation warning when compiled, and produces the following result when executed:
Sizeof( Age ) : 4
Age.age : 4
Age.age : 7
Age.age : 0
Calculate the number of bytes:
Example
#include
struct
example1
{
int
a
:
4
;
int
b
:
5
;
int
c
:
7
;
}
;
int
main
(
)
{
struct
example1 ex1
;
printf
(
"Size of example1: %zu bytes\n"
,
sizeof
(
ex1
)
)
;
return
0
;
}
In the example above, the example1 structure contains three bit-field members a, b, and c, occupying 4 bits, 5 bits, and 7 bits respectively.
The sizeof operator is used to compute the byte count of the example1 structure, and the result is printed:
Size of example1: 4 bytes
There are still the following points to note about the definition of bit-fields:
-
Bit-field members are stored in the same storage unit as much as possible; if the remaining space in that unit is not enough to hold the next bit-field, the bit-field is stored starting from the next unit.
You can also intentionally make a bit-field start from the next storage unit. For example:
struct bs{ unsigned a:4; unsigned :4; /* empty field / unsigned b:4; / starting from the next unit */ unsigned c:4; };
In this bit-field definition, a occupies the first 4 bits of the first byte, the last 4 bits are filled with 0 to indicate they are unused, b starts from the second byte and occupies 4 bits, and c occupies 4 bits.
-
The width of a bit-field cannot exceed the length of the data type it is attached to. Member variables all have a type, which limits the maximum length of a member variable,: so the number following it cannot exceed this length.
-
A bit-field can be unnamed, in which case it is used only for padding or position adjustment. An unnamed bit-field cannot be used. For example:
struct k{ int a:1; int :2; /* these 2 bits cannot be used */ int b:3; int c:2; };
From the above analysis, it can be seen that a bit-field is essentially a structure type, except that its members are allocated by bits.
Usage of Bit-fields
Bit-fields are used in the same way as structure members, with the general form:
位域变量名.位域名
位域变量名->位域名
Bit-fields can be output in various formats.
Please look at the following example:
Example
#include
int
main
(
)
{
struct
bs
{
unsigned
a
:
1
;
unsigned
b
:
3
;
unsigned
c
:
4
;
}
bit
,*
pbit
;
bit.
a
=
1
;
/* Assign values to bit-fields (note that the assigned value must not exceed the allowed range of the bit-field) */
bit.
b
=
7
;
/* Assign values to bit-fields (note that the assigned value must not exceed the allowed range of the bit-field) */
bit.
c
=
15
;
/* Assign values to bit-fields (note that the assigned value must not exceed the allowed range of the bit-field) */
printf
(
"%d,%d,%d\n"
,
bit.
a
,
bit.
b
,
bit.
c
)
;
/* Print the contents of the three fields in integer format */
pbit
=&
bit
;
/* Pass the address of the bit-field variable bit to the pointer variable pbit */
pbit
->
a
=
0
;
/* Use a pointer to reassign bit-field a to 0 */
pbit
->
b
&=
3
;
/* Uses the compound bitwise operator "&=", equivalent to: pbit->b=pbit->b&3. The original value of bit-field b is 7, and the result of the bitwise AND with 3 is 3 (111&011=011, decimal value 3) */
pbit
->
c
|=
1
;
/* Uses the compound bitwise operator "|=", equivalent to: pbit->c=pbit->c|1, resulting in 15 */
printf
(
"%d,%d,%d\n"
,
pbit
->
a
,
pbit
->
b
,
pbit
->
c
)
;
/* Print the values of these three fields using pointers */
return
0
;
}
When the code above is compiled and executed, it produces the following result:
1,7,15
0,3,15
The program above defines the bit-field structure bs, with three bit-fields a, b, and c, as well as a variable bit of type bs and a pointer variable pbit pointing to type bs.
This shows that pointers can also be used with bit-fields.