在c ++中将struct转换为int

Pai*_*doo 6 c++ can-bus

我有一个结构来表示具有位字段的29位CAN标识符如下.

struct canId
{
    u8 priority         :3; 
    u8 reserved         :1; 
    u8 dataPage         :1;     
    u8 pduFormat        :8;     
    u8 pduSpecific      :8;     
    u8 sourceAddress    :8;     
} iD;
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我想将此结构复制到整数变量.就像是:

int newId = iD; 
Run Code Online (Sandbox Code Playgroud)

但是我不确定这是否正确.有人可以对此发表评论吗?

编辑:我可以在每个字段上使用shift运算符,然后使用按位OR将它们放在正确的位置.但这首先使得位域结构的使用毫无用处.

Fer*_*eak 2

我希望我正确地完成了这个小魔术......你可能会这样做:

newID =  (int)iD.priority 
   | (int)(iD.reserved) << 3
   | (int)(iD.dataPage) << (3 + 1)
   | (int)(iD.pduFormat) << (3 + 1 + 1)
   | (int)(iD.pduSpecific) << (3 + 1 + 1 + 8)
   | (int)(iD.sourceAddress) << (3 + 1 + 1 + 8 + 8)
Run Code Online (Sandbox Code Playgroud)

但为此你需要一个int至少有 32 位的系统