Thursday, March 15, 2012

Test unsigned int for checking bit fields

A small but helpful tweak for C/C++ lovers.
Take an 8 bit integer variable:

unsigned char bitReg;

In bitReg, each 8 bit represents some meaning, so to test that first declare a structure:
enum regTest
{
    opIsRegular = 0x01,
    opIsNewData = 0x02,
    opIsRetry = 0x04,
    opHasOverhead = 0x08,
    opHasFlag1 = 0x10,
    opHasFlag2 = 0x20,
    opHasSpclRegOn = 0x40,
    opIsEnabled = 0x80
};

Notice that the hexadecimal value for each flag is carefully selected as hex values are as follows:

// 0x01 ==   1 == "00000001" // 0x02 ==   2 == "00000010" // 0x04 ==   4 == "00000100" // 0x08 ==   8 == "00001000" // 0x10 ==  16 == "00010000" // 0x20 ==  32 == "00100000" // 0x40 ==  64 == "01000000" // 0x80 == 128 == "10000000" 

Now each flag can be independently tested or set as follows:
 
bitReg = opIsRetry | opHasFlag2 | opIsEnabled           // value of bitReg will be 10100100
                       0x04            0x20                0x80                                 
 
The use of such method can make comparison easier as well. e.g.
if(bitReg & opIsEnabled) {   } // true
if(bitReg & opHasFlag1)  {   } // false