Question

I'm reading a tutorial of C (in french), and in a paragraph they talk about bit-fields, and they gave the following example without much explanation :

struct register {
   unsigned int mask : 3;
   signed int privilege : 6;
   unsigned int : 6; /* not used */
   unsigned int ov : 1;
};
  1. What is the result of this definition at memory level?

  2. Is there any pedagogical reason to have named the structure register in the example (this reminds me of electronics)?

  3. Why would someone declare a member like the one commented by "not used" in the example?

  4. What are the benefits of this structure in practice?

  5. Why doesn't a bits field have an address? Does this match to a specification in a Register?

Was it helpful?

Solution

This is especially useful in the Hardware where you want to create a Register of a module.

Now, Register has many bit-fields in it which can be of varying size in bits. So, you create a structure to represent the Register and the bit-fields. Basically registers in hardware are the structures which store the information about the module.

For Ex, for USB module the registers inside the USB hardware store the information about the status of the USB device and many other things.

By limiting the length of data members inside the struct to bits instead of reserving uints(or any other primitive data types) for the bit-fields as it occupies very less memory.

Also, the dummy declaration unsigned int : 6; is used to pad the structure so that the structure objects and the accesses are word aligned according to the machine architecture. Hence the access to the register objects doesn't consume more time if the accesses are aligned to the word boundary of the processor. Basically if the word, half-word or a byte is aligned at the address which is the multiples of the processor's word size then it is accessible very efficiently at a single stretch.

For example, in your case the Register is of 16-bits and it has 3 bit-fields: mask, privilege and ov. Whereas the remaining 6-bits are reserved for future use. Here it is how Register looks like,

bit-position     15  14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
                ---------------------------------------
                |ov |    reserved    | privilege |mask|
                ---------------------------------------

So, by making the structure of size 16-bits the objects of this structure can be easily accessible on a processor with 8,16,32 .... bit ALU's

OTHER TIPS

One example of where a structure like the one in the question could be used, is to emulate the bits of a hardware register (which is the likely use of this structure judging by the name).

For many small and embeddable systems, there may be hardware registers directly addressable in memory, and so structures such as these can be used to access bits directly in these registers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top