Last active
August 21, 2024 17:01
-
-
Save crosstyan/c9ebf59bdca0d422a04a175d605f1698 to your computer and use it in GitHub Desktop.
check bitfield order of struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdint> | |
#include <cstdio> | |
enum class StructBitfieldOrder { | |
/// the most significant bit as the first appearing field in a struct | |
MSB_AS_FIRST_FIELD, | |
/// the least significant bit as the first appearing field in a struct | |
LSB_AS_FIRST_FIELD, | |
/// should not happen | |
OTHER, | |
}; | |
/** | |
* @brief detect the bitfield order of the struct | |
* @note Assuming the compiler does not reorder the bitfields | |
*/ | |
StructBitfieldOrder struct_bitfield_order() { | |
struct t { | |
uint8_t zeros : 4 = 0b0000; | |
uint8_t ones : 4 = 0b1111; | |
}; | |
static_assert(sizeof(t) == 1); | |
static bool has_value = false; | |
static StructBitfieldOrder result = StructBitfieldOrder::OTHER; | |
if (has_value) { | |
return result; | |
} | |
constexpr auto test = t{ | |
.zeros = 0x0000, | |
.ones = 0b1111}; | |
if (const uint8_t test_raw = *reinterpret_cast<const uint8_t *>(&test); | |
test_raw == 0b00001111) { | |
result = StructBitfieldOrder::MSB_AS_FIRST_FIELD; | |
} else if (test_raw == 0b11110000) { | |
result = StructBitfieldOrder::LSB_AS_FIRST_FIELD; | |
} else { | |
result = StructBitfieldOrder::OTHER; | |
} | |
has_value = true; | |
return result; | |
} | |
const char *to_string(const StructBitfieldOrder order) { | |
switch (order) { | |
case StructBitfieldOrder::MSB_AS_FIRST_FIELD: | |
return "MSB_AS_FIRST_FIELD"; | |
case StructBitfieldOrder::LSB_AS_FIRST_FIELD: | |
return "LSB_AS_FIRST_FIELD"; | |
default: | |
return "OTHER"; | |
} | |
} | |
int main(){ | |
printf("%s", to_string(struct_bitfield_order())); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment