Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting at least one bit is set in collection of bitfields [duplicate]

In my program I have a C bit-field structure as:

 typedef struct
 {
    char a:1;
    char b:1;
    char c:1;
    char d:1;
 }_OpModes;
 _OpModes Operation; 

Now I want to check at least one of the flags is set in the above structure, If so do some operation otherwise return.

Though I can do this by checking bit by bit, that will be processor intensive for my Embedded application as structure of flags is big enough. I am looking for some operations such as (operation & 0xFF) to detect.

So can anyone suggest how to do this in C??

like image 866
Nagendra Babu Avatar asked Nov 22 '25 10:11

Nagendra Babu


1 Answers

There's no formally legal way to do it in one shot.

This is actually a situation in which "manual" implementation of bit-fields (i.e one multi-bit value with access through bitwise operators) is far superior to the language-level declaration of separate 1-bit bit-fields.

Even if you use language-level bit-fields, it is still a good idea to clump closely related flags together onto one larger bit-field instead of separate 1-bit fields (that is flags that have related semantics and thus might have to be processed together). E.g. in your case

#define FLAG_A 0x1
#define FLAG_B 0x2
#define FLAG_C 0x4
#define FLAG_D 0x8

typedef struct
{
    unsigned char abcd : 4;
} _OpModes;

If course, if that abcd is the only field in the struct, there's no real need to use a bit-field at all. Bit-fields exist for packing data, and if there's nothing there to pack, there's no need for bit-fields.

And prefer to use unsigned types for bit-fields unless you have a good reason to use a signed one. In your case, for signed char bit-fields you will end up with "flag" fields with values of 0 and -1. It can be made to work, but still looks weird.

like image 125
AnT Avatar answered Nov 24 '25 01:11

AnT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!