Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of declaring different datatypes inside bitfields?

Tags:

c

bit-fields

A typical use of bitfield is to declare a space efficient variable smaller than 8 bits. What i don't understand is the value of declaring those bits as short, int , long , bool etc. For example

typedef struct{
    int first:3,
    short second:3,
    char third:3
    } somestruct;

In above case, all 3 variables, i.e. first, second and third are 3 bit long. What is the value of declaring the variable first as int, second as short and third as char?

Or, why is even a data type required? I should be able to declare the above as

typedef struct{
    first:3,
    second:3,
    third:3
    } modifiedstruct;

The modifiedstruct assumes no datatype for the variables first, second and third. The responsibility of interpreting the 3 bits as character, numeric or floating should be responsibility of something else.

Both gcc and g++ on linux allow the above behavior.

like image 867
Jimm Avatar asked Oct 26 '25 17:10

Jimm


1 Answers

Actually, the C standard only allows bitfields to be of type signed int or unsigned int (and _Bool in C99). If you can throw a short, long or char in there, that's a compiler extension.

As to why, the main reason is signedness. Consider:

struct {
   int s: 3;
   unsigned u: 3;
} bf;

bf.s = 7;
bf.u = 7;

Both of these bitfields are all ones. However, C preserves sign, so:

(int)bf.s == -1    // Because signed conversions preserve the sign bit
bf.s >> 1 == -1    // So do right shifts on signed values

while:

(int)bf.u == 7     // Because the source is unsigned and so just a series of bits
bf.u >> 1 == 3     // Unsigned right shifts are just moving bits around as well

For compilers that allow char, it's probably the same sort of thinking. The default signedness of char is implementation-defined so if you want a bitfield's signedness to match your compiler's char's signedness, you can define it as char.

like image 50
Chris Reuter Avatar answered Oct 28 '25 07:10

Chris Reuter