David David - 1 year ago 74
C Question

Test for all bit fileds in C at once

Let's say I have a C structure defined as

struct data {
/* some memebers */

int flag_a:1;
int flag_b:1;
int flag_c:1;

/* some other members */

Is there a way to take advantage of the bitfields being represented as a single int in memory and write the condition
s.flag_a | s.flag_b | s.flag_c
as a simpler expression such as

Or would a smart compiler such as GCC be able to actually deduce it?

Edit: To make myself absolutely clear: I'm looking for a portable way to test for all the flags being set without explicitly testing each of the flags separately.

Answer Source

This isn't possible to do portably, in any deterministic way. The problem is that the C standard does not guarantee anything about those bits: you can't know which bit that is the LSB nor can you know if there is padding. On top of that, endianess is also an issue. (And in theory, different signedness formats.) See this for details.

In theory you could create a union between this bit field and one with : 3 bits, but the result of such practice will not be predictable nor well-defined.

The best solution is to get rid of the bit-field and replace it with a deterministic, 100% portable solution:

typedef struct
  uint8_t flags;
} data_t

#define FLAG_A 0x01u
#define FLAG_B 0x02u
#define FLAG_C 0x04u

data_t data = { .flags = FLAG_A | FLAG_B | FLAG_C};

if(data.flags & FLAG_ALL)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download