Challenge - 5 Problems
Bit Field Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of bit field structure size and values
What is the output of this C code when compiled and run on a typical 32-bit system?
Embedded C
typedef struct {
unsigned int a:3;
unsigned int b:5;
unsigned int c:6;
} Bits;
#include <stdio.h>
int main() {
Bits x = {5, 17, 33};
printf("Size: %zu\n", sizeof(x));
printf("a=%u b=%u c=%u\n", x.a, x.b, x.c);
return 0;
}Attempts:
2 left
💡 Hint
Remember that bit fields pack bits tightly and the size depends on total bits used.
✗ Incorrect
The struct has 3+5+6=14 bits total, which fits in 2 bytes. The values fit in their bit widths, so c=33 is stored correctly. Size is 2 bytes on typical systems.
🧠 Conceptual
intermediate1:30remaining
Bit field overflow behavior
Given this bit field declaration:
What happens if you assign x = 10; ?
unsigned int x:3;What happens if you assign x = 10; ?
Attempts:
2 left
💡 Hint
Think about how many bits 3 bits can hold and what happens to extra bits.
✗ Incorrect
A 3-bit unsigned field can hold values 0 to 7. Assigning 10 (binary 1010) keeps only the lowest 3 bits (010), which is 2.
🔧 Debug
advanced2:00remaining
Why does this bit field struct cause unexpected output?
Consider this code snippet:
What is the reason for the unexpected output of value?
typedef struct {
unsigned int flag:1;
unsigned int value:7;
} Data;
int main() {
Data d = {1, 130};
printf("flag=%u value=%u\n", d.flag, d.value);
return 0;
}What is the reason for the unexpected output of value?
Attempts:
2 left
💡 Hint
Check the maximum value storable in 7 bits and what happens if you assign a bigger number.
✗ Incorrect
7 bits can store max 127. Assigning 130 causes overflow and wraps around to 2 (130 - 128). So value prints as 2, which is unexpected.
📝 Syntax
advanced1:30remaining
Identify the syntax error in bit field declaration
Which option contains a syntax error in bit field declaration?
Attempts:
2 left
💡 Hint
Look carefully at the colon placement in bit field syntax.
✗ Incorrect
Option A has a misplaced colon after 'b;' which is invalid syntax. Bit field size must follow the variable name without extra semicolons.
🚀 Application
expert2:30remaining
Calculate total bits and size of nested bit field structs
Given these nested structs:
What is the output of the program?
typedef struct {
unsigned int x:4;
unsigned int y:4;
} Inner;
typedef struct {
Inner a;
unsigned int z:8;
} Outer;
#include
int main() {
printf("Size of Outer: %zu\n", sizeof(Outer));
return 0;
} What is the output of the program?
Attempts:
2 left
💡 Hint
Calculate total bits in Inner and Outer and consider alignment and padding.
✗ Incorrect
Inner has 4+4=8 bits (1 byte). Outer adds 8 bits (1 byte) for z, total 16 bits (2 bytes). But due to alignment on typical 32-bit systems, sizeof(Outer) is 4 bytes.