Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array inside a bit-packed struct

Tags:

c

gcc

bit-packing

I'd like to have an array inside of a bit-packed struct. I statically know the size of the array (32), and I'd like each element in the array to be a single bit. For example, I would like to be able to say something like:

struct example_s {
  // ...
  unsigned int flags[32] : 32;
} __attribute__((__packed__));

I've tried a couple things, but gcc won't budge. It would be nice to be able to do this so that I could write clean code that iterated over the elements in the packed array. Ideas?

like image 603
mhahnenb Avatar asked Feb 26 '23 17:02

mhahnenb


2 Answers

If you simply put it into a (32-bit) int, then you can cleanly iterate over the bits with a for loop like this:

for (bit = 0; bit < 32; bit++)
    flagValue = ((flags & (1<<bit)) != 0;

Not much harder to write than an array indexing syntax.

If you wish to hide the bit-twiddling to make the code more readable you could even use a function or macro to access the bits - e.g. GetFlag(bit)

like image 162
Jason Williams Avatar answered Mar 10 '23 08:03

Jason Williams


Bitfield member elements do not have addresses, so even if you could declare an array of them, there'd be no way to use it (all array access in C is pointer arithmetic and dereferencing). It's easy to code your own bit array using the bits of a larger type though; Jason has explained the basics. Generally you should avoid using bitfields unless you have a really good reason. They're usually more trouble than they're worth.

like image 42
R.. GitHub STOP HELPING ICE Avatar answered Mar 10 '23 09:03

R.. GitHub STOP HELPING ICE