I would like to model a status register in C/C++, which should be accessible as std::bitset and as std::uint8_t. Thus I would combine them as union as follows:
#include <bitset>
#include <iostream>
union byte {
std::uint8_t uint;
std::bitset<8> bitset;
};
int main(int, char*[])
{
byte b = { .uint = 0b10101010 };
std::cout << "Value of bit 5: "
<< (b.bitset.test(5) ? "true" : "false") << std::endl;
std::cout << "Value of bit 4: "
<< (b.bitset.test(4) ? "true" : "false") << std::endl;
std::cout << "Bitset Output: " << b.bitset << std::endl;
std::cout << "Uint Output: " << static_cast<int>(b.uint) << std::endl;
return 0;
}
This seems to work as expected, when compiled with GCC x86_64 8.2. However, I would like to know if I could expect this to work in all cases or if I am better off with some helper functions like bitset
, bittest
, ...