Search code examples
cinitializationvariable-assignmentstructurebit-fields

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

#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?

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.

So my question would be:

How does these initializations and assignments on whole structures work?

Also, why are the {} necessary?


Solution

  • int one:1;
    

    With this, you declare an int with only one bit which is used for the sign bit. So you see -1.

    If you want to store 3 (011), then you need to have 2 (data) +1(sign) bits in total. So, it should be:

    struct byte
    {
    int one:3;
    };
    

    Or use an unsigned int.

    struct byte
    {
    unsigned int one:2;
    };