Can I have a bit that references another part of a C bitfield?

Viewed 50

I am trying to come up with a code snippet where a property of a struct references a particular bit in another property of the same struct. This would look something like:

struct A {
    unsigned char type;
    unsigned char is_family_a : 1;  // should reference bit 7 of above somehow
};

struct A example;
example.type = 0x17;
printf("%i\n", example.is_family_a);  // 0
example.type = 0xF7;
printf("%i\n", example.is_family_a);  // 1

I looked at the cppreference page for it and didn't see anything. I also looked around stackoverflow, but didn't really find anything. This does seem to work if I use macros, but I think the compiler is likely to optimize this sort of thing better than I can.

1 Answers

This should do it:

struct A {
    union {
        unsigned char type;
        struct {
            unsigned char : 7;  // remove for big endian
            unsigned char is_family_a : 1;  // should reference bit 7 of above somehow
        };
    };
};
Related