Caution: this code is not compliant. Bjarne Straustrup says , and he should βknow that,β βObviously itβs illegal to write one member and then read another ...β Nevertheless, I leave this code for educational purposes ...
Here's an alternative that is useful when, say, you read your own binary protocol from a socket:
#include <cstdlib> union Value { struct { unsigned char a_ : 1; unsigned char b_ : 1; unsigned char c_ : 1; unsigned char d_ : 1; unsigned char e_ : 1; unsigned char f_ : 1; unsigned char g_ : 1; unsigned char h_ : 1; } bits_; unsigned char charVal_; }; int main() { unsigned char someValue = static_cast<unsigned char>(0x42); Value val; val.charVal_ = someValue; bool isBitDSet = val.bits_.d_; return 0; }
source share