将类型转换为整型c ++ [英] Type casting struct to integer c++

查看:234
本文介绍了将类型转换为整型c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

然后我可以设置 part2

word.part1 = 0; 
word.part2 = 9;
word.part3 = 0;

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

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);

如果我试图把它转换为一个普通的 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!

注意:必须使用c ++风格的转换,因为标准和其他...

Note: Must be done in c++ style casting, because of standards and whatnot... eye roll

推荐答案

尝试 reinterpret_cast< int>(word)转换运算符在用户定义的结构类型和 int 之间定义。

The attempt reinterpret_cast<int>(word) does not work because there is no conversion operator defined between your user-defined struct type and int.

您可以为结构添加转换运算符,或者最好使用IMHO命名函数进行转换,例如:

You could add a conversion operator to your struct, or preferably IMHO a named function to do the conversion, e.g.:

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;



注意,我使用无符号整数,因为他们在左移时有明确定义的行为。

Note, I used unsigned ints as they have well-defined behaviour on left shifting.

这篇关于将类型转换为整型c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆