Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitmask parameter naming conventions?

If I want to write a thread-safe method that simultaneously sets and clears some internal bits, I might do it with two arguments: a 32-bit mask of the internal bits to modify, and a 32-bit mask indicating whether to set the internal bits specified by the first parameter to 0 or 1.

What is the convention for naming these two parameters?

like image 256
snips-n-snails Avatar asked Nov 04 '22 06:11

snips-n-snails


1 Answers

I have not heard of any overall standards, although many places I have worked have had naming standards, etc.

Each bit in the mask gets defined individually, for example:

#define TANK_GAUGE_OK (0x80)  // 1 when the gauge is properly initialized and working
#define TANK_FULL     (0x08)  // 1 when tank is filled completely
#define TANK_HIGH     (0x04)  // 1 when tank is at least 1/4 full
#define TANK_LOW      (0x02)  // 1 when tank is at least 1/8 full
#define TANK_NOTEMPTY (0x01)  // 1 when there is some fuel in tank
#define TANK_LIGHTS_MASK (TANK_FULL | TANK_HIGH | TANK_LOW | TANK_NOTEMPTY )

For function names --

SET_ON(unsigned setMask), SET_OFF(unsigned clearMask)

To update specific bits in a register:

Update(changeMask, valueMask)

where changeMask contains the bits you want to update, to 1, and valueMask contains the bits values you want to set.

You would use them like this code for an embedded fuel gauge monitor:

static unsigned short fuelGaugeRegisterValue = 0x0000;
extern unsigned short *fuelGaugeRegister;

. . .

void UpdateFuelGauge(unsigned changeMask, unsigned valueMask) {
    // code to grab mutex goes here...
    fuelGaugeRegisterValue &= (~changeMask);
    fuelGaugeRegisterValue |= ( changeMask & valueMask);
    *fuelGaugeRegister = fuelGaugeRegisterValue;
    // code to release mutex goes here...
}

. . .

void SetFuelGaugeFromLevel(unsigned byte currentLevel)
    if ( currentLevel == 0xFF ) {
        UpdateFuelGauge( TANK_LIGHTS_MASK, TANK_LIGHTS_MASK );
    }
    else if (level >= 0x03 ) {
        UpdateFuelGauge( TANK_LIGHTS_MASK, (TANK_HIGH | TANK_LOW | TANK_NOTEMPTY) );
    }
    else if (level >= 0x02 ) {
        UpdateFuelGauge( TANK_LIGHTS_MASK, (TANK_LOW | TANK_NOTEMPTY) );
    }
    else if (level > 0x01 ) {
        UpdateFuelGauge( TANK_LIGHTS_MASK, TANK_NOTEMPTY );
    }
    else {
        UpdateFuelGauge( TANK_LIGHTS_MASK, 0 );
    }
}

Some other notes:

Try to name the bits and standard masks in a manner that you can make an educated guess as to what the bit would mean when it is "asserted". For instance, "EMPTY_FLAG" makes you guess as to whether "1" means "empty", of "not empty".

Wikipedia has an article on signal masking that uses some terminology, but currently it does mention any naming conventions.

like image 92
Jay Elston Avatar answered Nov 09 '22 04:11

Jay Elston