Game Development Reference

In-Depth Information

0101 (0x5)

~(0101) = 1010 (0xA)

We can use the inversion operator to clear a particular bit or bits from a value, if we com-

bine the inversion operator with the AND operator.

unsigned int value = FLAG0 | FLAG1 | FLAG2 | FLAG4; // 00010111

const unsigned int mask = ~(FLAG4); // 11101111

value &= mask; // 00000111

6.1.5 Left Shift <<

The shift operators move bits by the number of positions specified, the left shift operator

will shift the bits from the low bit to the high bit, bits below the shift will be set to 0 and

the bits shifted beyond the type's size are lost.

00000001 << 2

= 00000100

Left shifting can be used as an efficient way of performing multiplications by powers of

two. Shifting a value left by n bits has the effect of multiplying it by 2
n

6.1.6 Right Shift >>

Therightshiftisexactlythesameastheleftshift,exceptarightshiftoperatorwillshiftthe

bits from the high bit towards the low bit

00001101 >> 2

= 00000011

A right shift by n bits can be used to perform division by 2
n
.

The
Alignment
sectionhasanexampleusecaseinwhichenumflagsareuseful.Alignment

is an operation which can be combined, for example it is possible to align one element to

both the top and the left edges of some rectangle. Using enum flags allows us to reduce

the amount of code that would be necessary if each possible combination were to be im-

plementedindividually,andtheduplicationofcodewouldmakeitdifficulttomaintainand

understand.