Tuesday, January 10, 2012

The left shift operator isn't only useful for setting individual bits in a 32-bit value; it can also be used to 'read' a single bit from a larger valu

The left shift operator isn't only useful for setting individual bits in a 32-bit value; it can also be used to 'read' a single bit from a larger value, as you can see in the following code: unsigned long testValue = 0xFF00FF00;

// Check if the fifth bit is equal to 1 (hint: it isn't!)
if (testValue & (1 << 4))
{
// Fifth bit is equal to 1
}
else
{
// Fifth bit is equal to 0
}

Can you understand how this example code works? We are shifting a '1' bit 4 positions to the left (which will give us the following 32-bit value: 0000 0000 0000 0000 0000 0000 0001 0000). We are then 'comparing' this to our testValue with an & AND operator, which means that if bit 5 of our testValue is also 1 (as in the value we have just created), a '1' will be returned. If the values are different, the AND operator will fail and return 0.

No comments: