Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use bit-fields in C?

On the question 'why do we need to use bit-fields', searching on Google I found that bit fields are used for flags. Now I am curious,

  1. Is it the only way bit-fields are used practically?
  2. Do we need to use bit fields to save space?

Way of defining bit field from the book:

struct {     unsigned int is_keyword : 1;      unsigned int is_extern :  1;      unsigned int is_static : 1; } flags; 
  1. Why do we use int?
  2. How much space is occupied?

I am confused why we are using int, but not short or something smaller than an int.

  1. As I understand only 1 bit is occupied in memory, but not the whole unsigned int value. Is it correct?
like image 533
YohanRoth Avatar asked Jul 24 '14 12:07

YohanRoth


People also ask

Why do we use bit fields?

Bit fields can be used to reduce memory consumption when a program requires a number of integer variables which always will have low values. For example, in many systems storing an integer value requires two bytes (16-bits) of memory; sometimes the values to be stored actually need only one or two bits.

Why are bit fields usually implemented as fields within unions?

Bit-fields and unions may be combined in a way that permits programmers to pack and unpack bits in an integer. Unions allow programmers to circumvent C++'s strong typing rules while bit-fields allow programmers to access the bits that encode the compressed information.

Can we have an array of bit fields?

No, you can't. Bit field can only be used with integral type variables.


1 Answers

A quite good resource is Bit Fields in C.

The basic reason is to reduce the size used. For example if your write:

struct {     unsigned int is_keyword;      unsigned int is_extern;      unsigned int is_static; } flags; 

You will use at least 3 * sizeof(unsigned int) or 12 bytes to represent 3 little flags, that should only need 3 bits.

So if you write:

struct {     unsigned int is_keyword : 1;      unsigned int is_extern : 1;      unsigned int is_static : 1; } flags; 

This uses up the same space as one unsigned int, so 4 bytes. You can throw 32 one bit fields into the struct before it needs more space.

This is sort of equivalent to the classical home brew bit field:

#define IS_KEYWORD 0x01 #define IS_EXTERN  0x02 #define IS_STATIC  0x04 unsigned int flags; 

But the bit field syntax is cleaner, compare:

if (flags.is_keyword) 

against:

if (flags & IS_KEYWORD) 

and obviously less error prone.

like image 67
rioki Avatar answered Oct 13 '22 06:10

rioki