Bit mask operation not clear- what code is doing

Viewed 42

Any idea what this func returns? I'm not sure why it's shifted by 1 on the second line

Thanks

bool findWhat(U32 bitmask)
{
   U32 bitmaskOdd = bitmask & 0x55555555;
   U32 bitmaskEven = (bitmask & 0xAAAAAAAA) >> 1;
   U32 bitmaskXor = bitmaskOdd ^ bitmaskEven;
    
   if (bitmaskXor & bitmaskEven)
   {
     return TRUE;
   }
   return FALSE;
}
1 Answers

Take as example a bitmask with all four possible variants of adjacent bits in odd and even positions:

    8 7 6 5 4 3 2 1    Position (counted 1-based)
    0 0 0 1 1 0 1 1    bitmask

Resulting bitmaskOdd:

    0 0 0 1 0 0 0 1    bits in odd positions are kept

Resulting bitmaskEven without shift:

    0 0 0 0 1 0 1 0    bits in even positions are kept

Resulting bitmaskEven with shift:

    0 0 0 0 0 1 0 1    bits in even positions are kept but shifted

bitmaskXor as bitwise XOR of bitmaskEven and bitmaskOdd:

    0 0 0 1 0 1 0 0

Bitwise AND of bitmaskXor and bitmaskEven:

    0 0 0 0 0 1 0 0

As the AND is not zero, the function returns true. This indicates that there is an adjacent pair of bits in even and odd position where the even bit is set and the odd bit is not set.

In other words: The function returns true, if there is at least one 10 pair of adjacent bits, where the right-hand bit is in an odd position.

Related