Bit flags usage.

This information is more applicable to the C2C-plus and C2C++ compilers.
The BoostC and BoostC++ compilers have a built in bit data type.

The easiest way to work with flags is to declare each as a global 8-bit
variable like:
...
char flag1;
char flag2;
...

But this is acceptable only if you have plenty of RAM what usually is
not true. Only 1 bit in every flag is used and the other 7 bits are simply wasted.

A more improved method is to use logical operations to manipulate with flag bits.
Fortunatelly there are 'set_bit' and 'clear_bit' built-in functions which make the
life easier.

For example you need two flags in your program. The code may look like:

//Let's say you want to have two following flags
#define FLAG_1   0
#define FLAG_2   1

char flag; //Define a variable which will store these flags

main()
{
    char a, b;
 
    flag = 0; //clear all flags

    //Set the flag 1
    set_bit( flag, FLAG_1 );

    //Clear the flag 1
    clear_bit( flag, FLAG_1 );

    //Check if the flag 1 is set
    if( flag & (1<<FLAG_1) )
    {
        //Let's clear the variable a for example
        a = 0;
    }

    //Check if the flag 1 is clear
    if( (1<<FLAG_1) & (255 ^ (flag & (1<<FLAG_1))) )
    {
        //Let's clear the other variable b for example
        b = 0;
    }
}

Although the last if-expression looks complicated the generated code is shorter (7 instructions)
compared with the "if( (flag & (1<<FLAG_1))==0 )" which is 9 instructions long.
 

© 1998-2006 SourceBoost Technologies support@sourceboost.com