QUESTION 15
What is a bit-field?
2 marksAnswer
It is a structure or union member declared with a bit width, such as unsigned int ready : 1;. It can represent small integer state fields.
QUESTION 15
It is a structure or union member declared with a bit width, such as unsigned int ready : 1;. It can represent small integer state fields.
QUESTION 16
Bit-fields describe small-width integer members, often used for compact flags or bounded state values.
struct Flags {
unsigned int ready : 1;
unsigned int mode : 2;
};ready can hold 0 or 1. mode can hold 0 through 3 for this unsigned two-bit field. Access uses the normal dot or arrow member operators. Assign only values suitable for the field’s width and intended meaning.
The packing order and allocation-unit details are implementation-dependent. Do not use a bit-field structure as a portable network packet or file format without an explicit external encoding. A bit-field is not an addressable ordinary object: its address cannot be taken with &. sizeof cannot be applied to a bit-field expression.
For introductory portable declarations, use unsigned int, signed int or _Bool as appropriate. Plain int field signedness is implementation-defined. A zero-width unnamed field has a layout purpose and is not a normal named value. Do not promise a particular total byte saving: padding and packing rules vary.
The program assigns ready = 1 and mode = 3, then displays their promoted values. Each fixed field operation is O(1) in the usual model. Bit-fields improve a representation only when their restrictions fit the task.
/* CodeBhavya | Data Structures AR25 | Learning example */
#include <stdio.h>
struct Flags { unsigned int ready : 1; unsigned int mode : 2; };
int main(void)
{
struct Flags f = {0};
f.ready = 1; f.mode = 3;
printf("Ready = %u, mode = %u\n", (unsigned)f.ready, (unsigned)f.mode);
return 0;
}The example uses values in the code.
Ready = 1, mode = 3