[Asterisk-Dev] Patching flags to bitfield structs

Tilghman Lesher tilghman at mail.jeffandtilghman.com
Thu Jan 20 14:37:16 MST 2005


On Thursday 20 January 2005 14:54, Andrew Thompson wrote:
> Kevin P. Fleming wrote:
> > Andrew Thompson wrote:
> >> What they are talking about now, is putting all the variables that the
> >> flags were were supposed to represent back in as defined variables,
> >> but this time, using the variablename:X format to specify how many
> >> bits the variable should take up.
> >
> > Exactly. Let the compiler figure out how to combine 11 variables that
> > take up one or two bits each into storage in the struct, and let it
> > build the code to access them however it feels it best (as opposed to
> > using the existing macros). Where this really shines is in the cases
> > where have "flags" that have more than two values and require two bits
> > or more; the existing code for manipulating those is non-intuitive and
> > somewhat error-prone. Letting the compiler handle it would solve that
> > problem completely.
>
> Please forgive the newbie question, but, what happens if you overflow
> one of these bitpacked/storage optimized/colon number variables?
>
> Is the result undefined, or do they roll over like traditional
> variables? (I trust they won't screw up the next variable over in the
> structure, right?)
>
> It would be up to the developer to make sure they don't assign a new
> value to a "flag" that is larger than it can store. I know this is a
> duh-like statement, but it's a lot more likely to occur, in this
> instance than with just "int use_new_doodad;".

Easily proven:
#include <stdio.h>

int main(void)
{
        struct mybits {
                unsigned int foo:1;
                unsigned int bar:2;
        } mybits = { 0, 0 };
        int i;

        for (i=0; i<10; i++) {
                mybits.foo++;
                mybits.bar++;
                printf("foo=%d bar=%d\n", mybits.foo, mybits.bar);
        }
}

# ./bittest
foo=1 bar=1
foo=0 bar=2
foo=1 bar=3
foo=0 bar=0
foo=1 bar=1
foo=0 bar=2
foo=1 bar=3
foo=0 bar=0
foo=1 bar=1
foo=0 bar=2

-- 
Tilghman



More information about the asterisk-dev mailing list