C++, implicit truncation from 'int' to bit field

2.6k Views Asked by At

I want to create a 64-bit data structure that each bit(s) should contain a value. for that, I have created a struct as follows. (this is related to J1939 protocol and ControlApplication NAME just in case)

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*/

now I want to initialize an object instance of CA_NAME

CA_NAME j1939 = {};

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

Here I get realtime analysis error (I guess from ReSharper) that (i.e for the first assignment) enter image description here

What is the correct way of initializing an instance of the struct?

1

There are 1 best solutions below

0
On

The constant 0xFE0D32 has 24 value bits (and is indeed of type int).

You are trying to initialize an unsigned 21-bit bit-field IdentityNumber with a constant that exceeds its range. The compiler is kind enough to warn you of this potential mistake.

Furthermore, you compile as C++, which explains why:

  • CA_NAME j1939 = {}; does not generate an error in C++, but would in C. You do not actually need an initializer since j1939 is a global variable. If you insist on an explicit initializer, either provide the actual values or just write CA_NAME j1939 = { 0 };
  • The error message is abstruse, giving you a taste of the abysmal complexity of C++.