gpt4 book ai didi

c - 从低到高的位顺序/C 中带有位域的映射结构

转载 作者:太空宇宙 更新时间:2023-11-04 00:47:22 24 4
gpt4 key购买 nike

我最近在研究 C 中的位域,显然,位是从低到高排序的,尽管 Google 不支持这个论点(例如 Wikipedia。)

采用以下代码(http://ideone.com/UwWfJM):

#include <stdio.h>

struct bits {
unsigned char a : 1;
unsigned char b : 1;
unsigned char c : 1;
unsigned char d : 1;
unsigned char e : 1;
unsigned char f : 1;
unsigned char g : 1;
unsigned char h : 1;
};

int main(int argc, char **argv)
{
unsigned char c = 33;
struct bits *b = (struct bits *) &c;

printf("dec: %u\n", c);
printf("bits: %x", b->a);
printf("%x", b->b);
printf("%x", b->c);
printf("%x", b->d);
printf("%x", b->e);
printf("%x", b->f);
printf("%x", b->g);
printf("%x\n", b->h);

return 0;
}

输出是

dec: 33
bits: 10000100

...虽然我曾预计位顺序是相反的(即 00100001,首先是 MSB,最后是 LSB)。

有人可以解释这种行为吗?
此外,我是否可以假设映射总是朝这个方向?

注意:不是询问字节顺序,它是关于字节顺序的。我的问题的背景是我试图将缓冲区映射到结构。缓冲区包含一个 UDP 消息,由一个“位映射”组成(即“位置 x 的位意味着这个,位在位置 yz 就是那个意思,等等)。

谢谢!

最佳答案

根据 C standard 的 6.7.2.1 :

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

关于c - 从低到高的位顺序/C 中带有位域的映射结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32484944/

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