简体   繁体   English

初始化C中包含位域的结构

[英]Initilizing structures containing bit-fields in C

Im trying to understand a bit more about the workings of bitfields. 我试图进一步了解位域的工作原理。

Given the following code: And assuming int is 32 bits 给定以下代码:并且假设int是32位

#include <stdio.h>

int main()
{
    struct byte
    {
        int one:1;
    };
    struct byte var = {3};
    printf("%d\n", var.one);
    printf("%#x\n", var);
    return 0;
}

The output I get is: 我得到的输出是:

-1
0x1

However I was expecting to see: 但是我期望看到:

-1
0x3

Since 以来

struct byte var = {3};

is assigning the value 3 to the 4 bytes of int, isn't it? 将值3分配给int的4个字节,不是吗?

From the output I actually get it appears as if the above code line tries to store the value 3 into the 1 bit field hence printing 0x1 as the second output line. 从输出中我实际上得到的结果似乎是上述代码行试图将值3存储到1位字段中,因此将0x1打印为第二条输出行。

So my question would be: 所以我的问题是:

How does these initializations and assignments on whole structures work? 这些对整个结构的初始化和分配如何工作?

Also, why are the {} necessary? 另外,为什么{}必需的?

int one:1;

With this, you declare an int with only one bit which is used for the sign bit. 这样,您就可以声明只有一个位用于sign位的整数。 So you see -1 . 所以您看到-1

If you want to store 3 (011), then you need to have 2 (data) +1(sign) bits in total. 如果要存储3(011),则总共需要2(数据)+1(符号)位。 So, it should be: 因此,应为:

struct byte
{
int one:3;
};

Or use an unsigned int. 或使用unsigned int。

struct byte
{
unsigned int one:2;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM