什么是零宽度位字段 [英] What is zero-width bit field

查看:293
本文介绍了什么是零宽度位字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  的href=\"http://stackoverflow.com/questions/4297095/practical-use-of-zero-length-bitfields\">实际运用

Possible Duplicate:
Practical Use of Zero-Length Bitfields

为什么某些结构具有零宽度位字段,以及为什么需要它?

Why some structures have zero-width bit fields, and why is it required?

struct foo {
  int    a:3;
  int    b:2;
  int     :0; // Force alignment to next boundary.
  int    c:4;
  int    d:3;
};

int main()
{
        int i = 0xFFFF;
        struct foo *f = (struct foo *)&i;
        printf("a=%d\nb=%d\nc=%d\nd=%d\n", f->a, f->b, f->c, f->d);
        return 0;
}

上述程序的输出是

The output of above program is

manav@os-team:~/programs/test$ ./a.out
a=-1
b=-1
c=-8
d=0

请解释为什么这些数值是负的,而这些变量的结构内部的内存布局?

Please explain why these values are negative, and the memory layout of these variables inside the structure?

推荐答案

从<一个href=\"http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=%2Fcom.ibm.vacpp6m.doc%2Flanguage%2Fref%2Fclrc03defbitf.htm\">this首先击中了谷歌搜索:

0的长度位字段必须是未命名的。无名位字段不能引用或初始化。一个零宽度位字段可导致下一个字段到下一个容器的边界上对齐,其中容器是尺寸为基础类型的比特字段的相同。

至于你的问题的第二部分,你设置的在你的结构为全1位域的某些的,而且由于这些字段是签名,则这将导致这些字段为负值。你可以看到这个更有效,如果你整个结构设置为1秒,并期待在这两个符号和无符号重新presentations的值,例如

As for the second part of your question, you set some of the bitfields in your struct to all 1s, and since these fields are signed then this results in a negative value for these fields. You can see this more effectively if you set the entire struct to 1s and look at the values in both signed and unsigned representations, e.g.

int main()
{
    struct foo f;
    memset(&f, 0xff, sizeof(f));
    printf("a=%d\nb=%d\nc=%d\nd=%d\n", f.a, f.b, f.c, f.d); // print fields as signed
    printf("a=%u\nb=%u\nc=%u\nd=%u\n", f.a, f.b, f.c, f.d); // print fields as unsigned
    return 0;
}

这篇关于什么是零宽度位字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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