C / C ++:强制位字段顺序和对齐 [英] C/C++: Force Bit Field Order and Alignment

查看:199
本文介绍了C / C ++:强制位字段顺序和对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到位字段的结构内的顺序是特定的平台。那么如果我使用不同的编译器特有的包装选项,将在保证数据存储在正确的顺序,因为他们写的?例如:

I read that the order of bit fields within a struct is platform specific. What about if I use different compiler-specific packing options, will this guarantee data is stored in the proper order as they are written? For example:

struct Message
{
  unsigned int version : 3;
  unsigned int type : 1;
  unsigned int id : 5;
  unsigned int data : 6;
} __attribute__ ((__packed__));

在Intel处理器与GCC编译器,字段在内存中奠定了他们所示。 Message.version是在缓冲器中的前3位,和Message.type遵循。如果我发现了各种编译器等同结构包装选项,将在跨平台?

On an Intel processor with the GCC compiler, the fields were layed out in memory as they are shown. Message.version was the first 3 bits in the buffer, and Message.type followed. If I find equivalent struct packing options for various compilers, will this be cross-platform?

推荐答案

没有,也不会完全移植。对于结构包装选项扩展,而且其本身并不完全便携。除此之外,C99§6.7.2.1,第10段说:一单元(高阶到低阶或低阶到高阶)中位域的分配顺序是实现定义的。

No, it will not be fully-portable. Packing options for structs are extensions, and are themselves not fully portable. In addition to that, C99 §6.7.2.1, paragraph 10 says: "The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined."

即使是单一的编译器可能得不一样打好位字段根据目标平台的字节序,例如。

Even a single compiler might lay the bit field out differently depending on the endianness of the target platform, for example.

这篇关于C / C ++:强制位字段顺序和对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆