用C位域操纵 [英] Bitfield manipulation in C

查看:121
本文介绍了用C位域操纵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

测试和在C中的整数设置单独的比特的典型问题是也许有最常见的中间电平的编程技能。您可以设置和简单的位掩码,如

The classic problem of testing and setting individual bits in an integer in C is perhaps one the most common intermediate-level programming skills. You set and test with simple bitmasks such as

unsigned int mask = 1<<11;

if (value & mask) {....} // Test for the bit
value |= mask;    // set the bit
value &= ~mask;   // clear the bit

这是有趣的博客帖子指出,这是容易出错,难以维护和实践较差。 C语言本身提供位级别的访问是类型安全和便携:

An interesting blog post argues that this is error prone, difficult to maintain, and poor practice. The C language itself provides bit level access which is typesafe and portable:

typedef unsigned int boolean_t;
#define FALSE 0
#define TRUE !FALSE
typedef union {
        struct {
                boolean_t user:1;
                boolean_t zero:1;
                boolean_t force:1;
                int :28;                /* unused */
                boolean_t compat:1;     /* bit 31 */
        };
        int raw;
} flags_t;

int
create_object(flags_t flags)
{
        boolean_t is_compat = flags.compat;

        if (is_compat)
                flags.force = FALSE;

        if (flags.force) {
                [...]
        }
        [...]
}

但是,这使我的畏缩

有趣的论点我的同事和我有这个仍然没有得到解决。两种风格的工作,我保持经典掩码方法简单,安全,清晰。我的同事同意这是常见和容易的,但工会位域的方法是值得的额外的几行,使其便携和更安全。

The interesting argument my coworker and I had about this is still unresolved. Both styles work, and I maintain the classic bitmask method is easy, safe, and clear. My coworker agrees it's common and easy, but the bitfield union method is worth the extra few lines to make it portable and safer.

是否有任何一方的任何更多的参数?特别是有一些可能的失败,或许与字节顺序,该位掩码方法可能会错过,但其结构的方法是安全的?

Is there any more arguments for either side? In particular is there some possible failure, perhaps with endianness, that the bitmask method may miss but where the structure method is safe?

推荐答案

位字段都为您所想,为C没有给出机器字内字段的顺序的保证的The本C语言书中

Bitfields are not quite as portable as you think, as "C gives no guarantee of the ordering of fields within machine words" (The C book)

忽略,使用的正确的,这两种方法是安全的。这两种方法也允许积分变量的符号访问。你可以争辩说该位域方法更容易写,但也意味着更多的code审查。

Ignoring that, used correctly, either method is safe. Both methods also allow symbolic access to integral variables. You can argue that the bitfield method is easier to write, but it also means more code to review.

这篇关于用C位域操纵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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