Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use array of bit fields?

I am curious to know, Is it possible to use array of bit fields? Like:

struct st {   unsigned int i[5]: 4; };  
like image 823
msc Avatar asked Jan 29 '17 06:01

msc


People also ask

Is array of bit fields allowed justify your answer with an example?

5) Array of bit fields is not allowed. For example, the below program fails in the compilation.

Can bit fields used in data structure?

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.

Can we reference a bit field?

Pointers and non-const references to bit-fields are not possible.


2 Answers

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

C11-§6.7.2.1/5

A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed int, unsigned int, or some other implementation-defined type.

Alternatively you can do this

struct st {     unsigned int i: 4;   } arr_st[5];  

but its size will be 5 times the size of a struct (as mentioned in comment by @Jonathan Leffler) having 5 members each with bit field 4. So, it doesn't make much sense here.

More closely you can do this

struct st {     uint8_t i: 4;   // Will take only a byte } arr_st[5];  
like image 187
haccks Avatar answered Sep 19 '22 10:09

haccks


C does not support arrays of bit-fields, so the short answer is no.

For very large arrays, it might be worthwhile to pack values, 2 per byte, this way:

#define ARRAY_SIZE  1000000  unsigned char arr[(ARRAY_SIZE + 1) / 2];  int get_4bits(const unsigned char *arr, size_t index) {     return arr[index >> 1] >> ((index & 1) << 2); }  int set_4bits(unsigned char *arr, size_t index, int value) {     arr[index >> 1] &= ~ 0x0F << ((index & 1) << 2);     arr[index >> 1] |= (value & 0x0F) << ((index & 1) << 2); } 
like image 41
chqrlie Avatar answered Sep 21 '22 10:09

chqrlie