Skip to content

Instantly share code, notes, and snippets.

@kevinkreiser
Created October 17, 2015 18:08
Show Gist options
  • Save kevinkreiser/2de59b0aab235cd45279 to your computer and use it in GitHub Desktop.
Save kevinkreiser/2de59b0aab235cd45279 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <cinttypes>
#include <limits>
//combining a union with an anonymous bit field we can:
// get a summary value for the entire bit field
// reference bit field members directly from the union
// use an initializer list to set them
//TODO: how to initialize via the bit field members without un-anonymizing it
union bit_funion_t {
uint8_t all;
struct {
uint8_t front:4;
uint8_t back:4;
};
};
int main(void) {
bit_funion_t b{std::numeric_limits<uint8_t>::max()};
std::cout << "size: " << sizeof(bit_funion_t) << std::endl;
std::cout << "front bits: " << static_cast<int>(b.front) << std::endl;
std::cout << "back bits: " << static_cast<int>(b.back) << std::endl;
std::cout << "all bits: " << static_cast<int>(b.all) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment