C ++,从“INT”至比特字段隐含截断

问题描述 投票:0回答:1

我想创建一个64位的数据结构,每个位(一个或多个)应包含的值。对于这一点,我已经创建了一个结构如下。 (这是关系到J1939协议和ControlApplication NAME以防万一)

typedef struct CA_NAME {
    unsigned  IdentityNumber : 21;          // 21 bits  Byte 1.1 to 3.5 
    unsigned  ManufactorerCode : 11;        // 11 bits  Byte 3.6 to 4.8 
    unsigned  ECUInstance : 3;              // 3  bits  Byte 5.1 to 5.3 
    unsigned  functionInstance : 5;         // 5  bits  Byte 5.4 to 5.8 
    unsigned  Function : 8;                 // 8  bits  Byte 6          
    unsigned  Reserved : 1;                 // 1  bit   Byte 7.1        
    unsigned  VehicleSystem : 7;            // 7  bits  Byte 7.2 to 7.8 
    unsigned  VehicleSystemInstance : 4;    // 4  bits  Byte 8.1 to 8.4 
    unsigned  IndustryGroup : 3;            // 3  bits  Byte 8.5 to 8.7 
    unsigned  ArbitraryAddressCapable : 1;  // 1  bit   Byte 8.8        
} CA_NAME; /*64Bit NAME*/

现在我想初始化CA_NAME的对象实例

CA_NAME j1939 = {};

void Create_CA_NAME() {
    j1939.IdentityNumber = 0xFE0D32;
    j1939.ManufactorerCode = 0x57;
    ....
}

在这里,我得到实时分析错误(我从ReSharper的猜测)即(即首次转让)enter image description here

什么是初始化结构的实例的正确方法?

c struct bit-fields bitstuffing
1个回答
0
投票

恒定0xFE0D32有24个值的比特(并且是类型int的确实)。

您正试图超过其范围内的恒定初始化一个无符号21位位字段IdentityNumber。编译器是一种足以提醒你这种潜在的错误。

此外,您编译为C ++,这就解释了为什么:

  • CA_NAME j1939 = {};不会产生在C ++中的错误,但会在C.你实际上并不需要的初始化,因为j1939是一个全局变量。如果你坚持明确的初始化,要么提供的实际值或只写CA_NAME j1939 = { 0 };
  • 该错误消息是abstruse,为您提供C ++的深不可测的复杂的味道。
© www.soinside.com 2019 - 2024. All rights reserved.