【问题标题】:Which bits are which in a struct with bitfields?具有位域的结构中的哪些位?
【发布时间】:2014-09-09 07:31:56
【问题描述】:
#include <string.h>
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

typedef struct AA {
    int a1:5;
    int a2:2;
} AA;

int main() {
    AA aa;
    char cc[100];
    strcpy(cc, "0123456789");
    memcpy(&aa, cc, sizeof(AA));
    printf("%d\n", aa.a1);
    printf("%d\n", aa.a2);
    return 0;
}

我的意思是我知道sizeof(AA)sizeof(int)等于4字节,并且在将"0123"复制到aa之后二进制数是

00110011,00110010,00110001,00110000
    3         2        1         0

但我不明白哪些位是a1:5a2:2

【问题讨论】:

    标签: c structure bit-fields


    【解决方案1】:

    位域的排列不是标准化的。

    根据您的结果,a1 持有 10000a2 持有 01。可能出现这种情况的一种方法是,a1cc[0] 的最低 5 位,而a2 是次低的 2 位。

    cc[0] 就是00110000 被划分为0 01 10000

    如果您对值进行了更多实验,您可以确定编译器使用的顺序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      相关资源
      最近更新 更多