Type casting struct to integer C ++

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

+6
source share
3 answers
 union Ints { struct { int part1 : 10; int part2 : 6; int part3 : 16; } word; uint32_t another_way_to_access_word; }; 

may I help

+5
source

Trying reinterpret_cast<int>(word) does not work because there is no conversion operator defined between your custom structure type and int .

You can add a conversion operator to your structure or, preferably, an IMHO named function for conversion, for example:

 struct { uint32_t part1 : 10; uint32_t part2 : 6; uint32_t part3 : 16; uint32_t get_all_parts() const { return (part1 << 22) + (part2 << 16) + part3; } } word; 

Notice I used unsigned ints as they have well-defined left shift behavior.

+3
source
 typedef struct word { uint32_t part1 : 10; uint32_t part2 : 6; uint32_t part3 : 16; operator int(){ return (part1 << 22) + (part2 << 16) + part3; } struct word operator=(int i){ this->set(i); return *this; } void set(int i){ part1 = (0xFFFF0000 & i) >> 16; part2 = (0x0000FC00 & i) >> 10; part3 = (0x000003FF & i); } word(int i){ this->set(i); } } word; 

That should do it.

 struct word myword = 20; struct word second_word(50); myword = 10; second_word.set(50); int x = myword; iny y = second_word; 

Note. I checked it out. It compiles fine. And it works great.

+3
source

Source: https://habr.com/ru/post/975004/


All Articles