I have a design that requires values to be contained at certain bits inside of a 32 bit word. Example being bits 10-15 must hold value 9, with the remaining bits all being 0. So for simplicity/readability I created a struct that contains a broken down version of what is asked.
struct {
int part1 : 10;
int part2 : 6;
int part3 : 16;
} word;
I can then set part2
to be equal to whatever value is requested, and set the other parts as 0.
word.part1 = 0;
word.part2 = 9;
word.part3 = 0;
I now want to take that struct, and convert it into a single 32 bit integer. I do have it compiling by forcing the casting, but it does not seem like a very elegant or secure way of converting the data.
int x = *reinterpret_cast<int*>(&word);
If I try to cast it just as a normal 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 of doing this, I just can not figure it out. Thanks in advance!
Note: Must be done in c++ style casting, because of standards and whatnot... eye roll