NexWo NexWo - 1 month ago 7
C Question

Bit field memory usage in C

Why does it return with 96 and not 64?
If I sum bit of bit field I will get 64.

Edited:

The

var
variable has
0xFFFFFF
and not
0xFFFFFFFF
.
-> The
var
variable has
0x3FFFFFFF00FFFFFF
and not
0xFFFFFFFFFFFFFFFF
.*

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

typedef struct{
uint32_t a : 24;
uint32_t b : 20;
uint32_t c : 10;
uint32_t d : 6;
uint32_t e : 4;
}MyType_t;

int main(){
MyType_t test;
test.a = -1;
test.b = -1;
test.c = -1;
test.d = -1;
test.e = -1;

uint64_t var = *((uint64_t*)&test);

printf("MyType_t: %d bit\n", sizeof(MyType_t) * 8);//96 bit
printf("Var: %#llX\n", var);//0x3FFFFFFF00FFFFFF
return 0;
}


This code will be worked correctly:

typedef struct{
uint32_t a : 16;
uint32_t b : 16;
uint32_t c : 16;
uint32_t d : 8;
uint32_t e : 8;
}MyType_t;

Answer

The fields a and b cannot possibly fit into a single type of uint32_t:

typedef struct{
    uint32_t a : 24;    //first 32 bits
    uint32_t b : 20;    //second 32 bits
    uint32_t c : 10;    //
    uint32_t d : 6;     //third 32 bits
    uint32_t e : 4;     //
}MyType_t;

so the size of the struct is three times the size of uint32_t.


The behavior of the code uint64_t var = *((uint64_t*)&test); is not defined.