0 day streak
cpp / intermediate
Snippet

Space-Optimized Structures via Bit-fields

Bit-fields allow precise control over data representation by restricting members to a specific bit width, which is useful for memory-efficient flag storage or hardware interfacing.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
struct DeviceStatus {
// Use only the specified number of bits for each member
unsigned int powerOn : 1;
unsigned int error : 1;
unsigned int mode : 3; // Allows values 0-7
};
int main() {
DeviceStatus status = {1, 0, 5};
std::cout << "Size of struct: " << sizeof(status) << " bytes" << std::endl;
if (status.powerOn) {
std::cout << "Mode: " << status.mode << std::endl;
}
return 0;
}
Breakdown
1
unsigned int powerOn : 1;
Allocates exactly 1 bit for the powerOn flag instead of a full integer or boolean byte.
2
unsigned int mode : 3;
Allocates 3 bits, permitting a range of 8 distinct values (0 through 7).