有理由避免使用位域结构成员吗? [英] Are there reasons to avoid bit-field structure members?

查看:106
本文介绍了有理由避免使用位域结构成员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很早就知道C中有位域,偶尔我会用它们来定义密集的结构:

I long knew there are bit-fields in C and occasionally I use them for defining densely packed structs:

typedef struct Message_s {
     unsigned int flag : 1;
     unsigned int channel : 4;
     unsigned int signal : 11;
} Message;

当我阅读开放源代码时,我经常会发现要存储的位掩码和移位操作并在手卷位字段中检索此类信息。这是如此普遍,以至于我认为作者并不了解位域语法,因此我想知道是否有理由通过位掩码和自己的移位操作来滚动位域,而不是依靠编译器来生成位域

When I read open source code, I instead often find bit-masks and bit-shifting operations to store and retrieve such information in hand-rolled bit-fields. This is so common that I do not think the authors were not aware of the bit-field syntax, so I wonder if there are reasons to roll bit-fields via bit-masks and shifting operations your own instead of relying on the compiler to generate code for getting and setting such bit-fields.

推荐答案


为什么其他程序员使用手工编码的位

Why other programmers use hand-coded bit manipulations instead of bitfields to pack multiple fields into a single word?

此答案是基于观点的,因为问题很开放:

This answer is opinion based as the question is quite open:


  • 许多程序员都不知道位域的可用性,也不确定它们的可移植性和精确的语义。一些人甚至不信任编译器产生正确代码的能力。他们喜欢编写自己理解的显式代码。

  • Many programmers are unaware of the availability of bitfields or unsure about their portability and precise semantics. Some even distrust the compiler's ability to produce correct code. They prefer to write explicit code that they understand.

正如Cornstalks所说,这种态度植根于现实生活中的经验如本文所述

As commented by Cornstalks, this attitude is rooted in real life experience as explained in this article.

位域的实际内存布局是实现定义的:如果内存布局必须遵循精确的规范,不得使用位域,并且可能需要手动编码的位操作。

Bitfield's actual memory layout is implementation defined: if the memory layout must follow a precise specification, bitfields should not be used and hand-coded bit manipulations may be required.

带符号值的处理在有符号类型位域中定义实现。如果将带符号的值打包到一系列位中,则对访问函数进行手工编码可能会更可靠。

The handing of signed values in signed typed bitfields is implementation defined. If signed values are packed into a range of bits, it may be more reliable to hand-code the access functions.

这篇关于有理由避免使用位域结构成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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