Bit fields can be used to reduce memory consumption when a program requires a number of integer variables which always will have low values. For example, in many systems storing an integer value requires two bytes (16-bits) of memory; sometimes the values to be stored actually need only one or two bits.
The smallest group of bits the language allows use to work with is the unsigned char , which is a group of 8 bits.
These space-saving structure members are called bit fields, and their width in bits can be explicitly declared. Bit fields are used in programs that must force a data structure to correspond to a fixed hardware representation and are unlikely to be portable.
In programming terminology, a bit field is a data structure that allows the programmer to allocate memory to structures and unions in bits in order to utilize computer memory in an efficient manner. Since structures and unions are user-defined data types in C, the user has an idea of how much memory will they occupy.
I just want to know about following structure declarations. Which one is better to use for memory allocation and why? And what about padding in case of unsigned char and unsigned int?
struct data{
unsigned char a:3;
unsigned char b:4;
};
and
struct data{
unsigned int a:3;
unsigned int b:4;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With