输入struct struct to integer c ++

MZi*_*an6 8 c++ struct

我的设计要求在32位字内的某些位中包含值.位10-15的示例必须保持值9,其余位都为0.因此,为了简单/可读性,我创建了一个包含所询问内容的细分版本的结构.

struct {
    int part1 : 10;
    int part2 : 6;
    int part3 : 16;
} word;
Run Code Online (Sandbox Code Playgroud)

然后我可以设置part2为等于请求的任何值,并将其他部分设置为0.

word.part1 = 0; 
word.part2 = 9;
word.part3 = 0;
Run Code Online (Sandbox Code Playgroud)

我现在想要采用该结构,并将其转换为单个32位整数.我确实通过强制转换来编译它,但它似乎不是一种非常优雅或安全的转换数据的方式.

int x = *reinterpret_cast<int*>(&word);
Run Code Online (Sandbox Code Playgroud)

如果我尝试像平常一样投射它,reinterpret_cast<int>(word)我会收到以下错误:

invalid cast from type 'ClassName::<anonymous struct>' to type 'int'
Run Code Online (Sandbox Code Playgroud)

必须有更好的方法来做到这一点,我无法弄明白.提前致谢!

注意:必须以c ++风格的方式进行,因为标准和诸如此类的东西...... 眼睛滚动

Dmi*_*nik 6

union Ints {
  struct {
    int part1 : 10;
    int part2 : 6;
    int part3 : 16;
 } word;
 uint32_t another_way_to_access_word;
};
Run Code Online (Sandbox Code Playgroud)

可能有帮助