Most Asked Bit Field Interview Questions
Q1. Predict the output of the following program. Assume that unsigned int takes 4 bytes and long int takes 8 bytes.
Ans:
C
#include <stdio.h>
struct
test {
// Unsigned integer member x
unsigned
int
x;
// Bit-field member y with 33 bits
unsigned
int
y : 33;
// Unsigned integer member z
unsigned
int
z;
};
int
main()
{
// Print the size of struct test
printf
(
"%lu"
,
sizeof
(
struct
test));
return
0;
}
Error:
./3ec6d9b7-7ae2-411a-a60e-66992a7fc29b.c:4:5: error: width of 'y' exceeds its type unsigned int y : 33; ^
Q2. Predict the output of the following program.
Ans:
C
#include <stdio.h>
struct
test {
// Unsigned integer member x
unsigned
int
x;
// Bit-field member y with 33 bits
long
int
y : 33;
// Unsigned integer member z
unsigned
int
z;
};
int
main()
{
// Declare a variable t of type struct test
struct
test t;
// Pointer to unsigned int, pointing to member x
unsigned
int
* ptr1 = &t.x;
// Pointer to unsigned int, pointing to member z
unsigned
int
* ptr2 = &t.z;
// Print the difference between the two pointers
printf
(
"%d"
, ptr2 - ptr1);
return
0;
}
Output
4
Q3. Predict the output of the following program.
Ans:
C
#include <stdio.h>
union
test {
// Bit-field member x with 3 bits
unsigned
int
x : 3;
// Bit-field member y with 3 bits
unsigned
int
y : 3;
// Regular integer member z
int
z;
};
int
main()
{
// Declare a variable t of type union test
union
test t;
// Assign the value 5 to x (3 bits)
t.x = 5;
// Assign the value 4 to y (3 bits)
t.y = 4;
// Assign the value 1 to z (32 bits)
t.z = 1;
// Print the values of x, y, and z
printf
(
"t.x = %d, t.y = %d, t.z = %d"
, t.x, t.y, t.z);
return
0;
}
Outputt.x = 1, t.y = 1, t.z = 1
Bit Fields in C
In C, we can specify the size (in bits) of the structure and union members. The idea of bit-field is to use memory efficiently when we know that the value of a field or group of fields will never exceed a limit or is within a small range. C Bit fields are used when the storage of our program is limited.
Need of Bit Fields in C
- Reduces memory consumption.
- To make our program more efficient and flexible.
- Easy to Implement.