C++ Bit Masking

C++ Bit Masking


The following is a simple code example for decoding a 32 bit unsigned integer into Year , Month, Day, and some arbitrary "Sequence" number. In this example, 12 bits are used for the Year, 4 bits for the Month, and 16 bits for the "Sequence" number.


// Do some bitmasking

quint32 bits = 0x7DD50002; // Example


// 32 bits and we want the top 12

// 32 28 24 20 16 12 8 4

// 0x F F F 0 0 0 0 0

quint32 yearMask = 0xFFF00000;

quint32 monthMask = 0x000F0000;

quint32 sequenceMask = 0x0000FFFF;


// Extract the sets

quint32 yearSet = ( yearMask & bits ) >> 20;

quint32 monthSet = ( monthMask & bits ) >> 16;

quint32 sequenceSet = sequenceMask & bits;


qDebug() << "Year is: " << yearSet << " Month is: " << monthSet << " Sequence is: " << sequenceSet;




ClassyBits 2016