C中的位字段内存使用情况

0 c struct field bit

为什么它以96而不是64返回?如果我对比特字段的总和,我将得到64.

编辑:

该var变量0xFFFFFF,而不是0xFFFFFFFF.- > var变量有0x3FFFFFFF00FFFFFF没有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;
}
Run Code Online (Sandbox Code Playgroud)

此代码将正常工作:

typedef struct{
    uint32_t a : 16;
    uint32_t b : 16;
    uint32_t c : 16;
    uint32_t d : 8;
    uint32_t e : 8;
}MyType_t;
Run Code Online (Sandbox Code Playgroud)

250*_*501 6

字段a和b不可能适合单一类型的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;
Run Code Online (Sandbox Code Playgroud)

所以struct的大小是uint32_t大小的三倍.


uint64_t var = *((uint64_t*)&test);未定义代码的行为.