So as an example. The smallest thing you can address in C++ is a byte, and so attempting to access for example any of the 1 bit uint8_t
's inside this bitField
is not legal.
#include <iostream>
#include <cstdint>
struct bitField {
uint8_t n0 : 1;
uint8_t n1 : 1;
uint8_t n2 : 1;
uint8_t n3 : 1;
uint8_t n4 : 1;
uint8_t n5 : 1;
uint8_t n6 : 1;
uint8_t n7 : 1;
};
int main() {
bitField example;
// Can address the whole struct
std::cout << &example << '\n'; // FINE, addresses a byte
// Can not address for example n4 directly
std::cout << &example.n4; // ERROR, Can not address a bit
// Printing it's value is fine though
std::cout << example.n4 << '\n'; // FINE, not getting address
return 0;
}
As TheDude mentioned in the comment section however, the STL has a class std::bitset<N>
which offers a workaround for this. It basically wraps an array of bools. Still, the end result is indexing bytes, not bits.