I am curious to know, Is it possible to use array of bit fields? Like:
struct st { unsigned int i[5]: 4; };
5) Array of bit fields is not allowed. For example, the below program fails in the compilation.
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.
Pointers and non-const references to bit-fields are not possible.
No, you can't. Bit field can only be used with integral type variables.
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];
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With