Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is zero-width bit field [duplicate]

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?

like image 387
manav m-n Avatar asked Dec 10 '12 14:12

manav m-n


People also ask

What is mean by empty bit field?

There are a number of reasons you might see an empty bit field. They might be reserved for some future use, such as expanding the existing fields without having to change their offsets.

What is meant by bit field?

A bit field is a data structure that consists of one or more adjacent bits which have been allocated for specific purposes, so that any single bit or group of bits within the structure can be set or inspected.

What is a bit field in C?

Both C and C++ allow integer members to be stored into memory spaces smaller than the compiler would ordinarily allow. These space-saving structure members are called bit fields, and their width in bits can be explicitly declared.

What is bit field in Java?

public class BitField extends Object. Supports operations on bit-mapped fields. Instances of this class can be used to store a flag or data within an int , short or byte . Each BitField is constructed with a mask value, which indicates the bits that will be used to store and retrieve the data for that field.


1 Answers

From this first hit on a Google search:

Bit fields with a length of 0 must be unnamed. Unnamed bit fields cannot be referenced or initialized. A zero-width bit field can cause the next field to be aligned on the next container boundary where the container is the same size as the underlying type of the bit field.

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;
}
like image 66
Paul R Avatar answered Oct 23 '22 09:10

Paul R