Pawel Veselov
Pawel Veselov

Reputation: 4225

How can I span bit field across a union?

Here is the structure I want:

typedef struct someip_header { 
    union { 
        uint32_t message_id;
        struct {
            uint16_t service_id; 
            uint8_t for_rpc : 1; 
            union {
                uint16_t method_id : 15;
                uint16_t event_id : 15;
            };
        };
    };
} someip_header_t;

(The reason is that if for_rpc is 1, then the last 15 bits mean event ID, otherwise they mean method ID)

But the size of this structure is 5 bytes (packed), I guess because the compiler won't put union unaligned. If I replace the inner union with just a uint16_t val : 15, the size gets back to 4 bytes as expected:

typedef struct someip_header { 
    union { 
        uint32_t message_id;
        struct {
            uint16_t service_id; 
            uint8_t for_rpc : 1; 
            uint16_t method_event_id : 15;
        };
    };
} someip_header_t;

Just wondering, is there a way to pack this? It's really only cosmetic, but still...

Upvotes: 3

Views: 101

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

Form the union at the byte level:

typedef struct someip_header { 
    union { 
        uint32_t message_id;
        struct {
            uint16_t service_id; 
            union {
                struct {
                    uint8_t for_rpc : 1; 
                    uint16_t method_id : 15;
                };
                struct {
                    uint8_t for_rpc_2 : 1; 
                    uint16_t event_id : 15;
                };
            };
        };
    };
} someip_header_t;

Upvotes: 2

Related Questions