How to check for a single field being set in a C bitfield -
i have following style of union - defined in interface not easy change.
i want check if foo field being set. , don't want itemizing other fields.
so immediate thoughts construct mask, bitfield doing it's best hide details position of named field.
i couldn't think of better creating variable 1 field set , inverting raw field. there neater solution?
typedef union struct { unsigned char user:1; unsigned char zero:1; unsigned char foo:1; unsigned char bar:1; unsigned char blah:1; unsigned char unused:3; }; unsigned char raw; } flags_t;
bitwise xor negation of want:
11011111 ^ 00100000 = 11111111
then check value == 255. can make clean using own struct build negation setting bar->foo = 0 , else 1.
edit: little elaboration because feel bad not being pretty when that's you're asking for:
struct { unsigned char bad:1; unsigned char bad:1; unsigned char foo; unsigned char other:1; unsigned char bad:1; unsigned char things:3; } state_checker; int some_checking_function(flags_t possible_foo) { result = possible_foo ^ state_checker; result = !(result - 255u); return result; }
ideally make constant uses same struct value you're checking uses, make sure nothing wonky happens @ compile time, basic idea.
Comments
Post a Comment