I have a project that requires values ββto be contained in specific bits within a 32-bit word. The example, which is bits 10-15, should contain the value 9, and the remaining bits are all 0. Therefore, for simplicity / readability, I created a structure containing a broken version of what is given.
struct { int part1 : 10; int part2 : 6; int part3 : 16; } word;
Then I can set part2 to any requested value and set the rest of the parts to 0.
word.part1 = 0; word.part2 = 9; word.part3 = 0;
Now I want to take this structure and convert it to a single 32-bit integer. I have it compiled by forcing casting, but it doesn't seem like a very elegant or secure way to convert data.
int x = *reinterpret_cast<int*>(&word);
If I try to apply it as a regular reinterpret_cast<int>(word) , I get the following error:
invalid cast from type 'ClassName::<anonymous struct>' to type 'int'
There must be a better way to do this, I just can't figure it out. Thanks in advance!
Note. Should be done in C ++ style casting, due to standards and something else ... eye roll
source share