gpt4 book ai didi

c++ - 位字段结构分配意外行为

转载 作者:太空狗 更新时间:2023-10-29 23:25:44 26 4
gpt4 key购买 nike

我不知道为什么,但位域分配没有按预期工作。可能只是一个愚蠢的事情,但我一直无法找到问题。

我们非常欢迎任何帮助。

typedef struct  a {
unsigned char a1 :1;
unsigned char a2 :3;
unsigned char a3 :2;
unsigned char a4 :2;
} __attribute__((packed)) mystruct;

int main() {
mystruct d;
d.a1 = 0;
d.a2 = 2;
d.a3 = 1;
d.a4 = 2;

unsigned char *val = (unsigned char*) &d;

printf("%02X \n", *val);
printf("%02X \n", sizeof(hola));

exit(0);
}

返回的输出:

94
01

预期输出:

26
01

最佳答案

几乎所有关于位域的内容都是实现定义的。尤其是一个单元中的位顺序。

(C99, 6.7.2.1p10) "The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined."

在您的实现中,这些位首先存储在单位 lsb(最低有效位)中,而不是像您期望的那样首先存储 msb(最高有效位)。

你拥有的是:

[a1.0] [a2.0] [a2.1] [a2.2] [a2.0] [a3.1] [a4.0] [a4.1] 
0 0 1 0 1 0 0 1
bit 0 - bit 7

lsb - msb

如果您认为最左边的位是最低有效位,则为 0x94

关于c++ - 位字段结构分配意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10128044/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com