GOOC - Game Oriented Object C

GOOC - Game Oriented Object C

Next: Bitwise Logical Operators, Previous: Logical Operators, Up: Expressions and Operators
[Contents]

7.5. Bitwise Shift Operators

7.5. Bitwise Shift Operators

You use the left-shift operator << to shift its first operand’s bits to the left. The second operand denotes the number of bit places to shift. Bits shifted off the left side of the value are discarded; new bits added on the right side will all be 0. (The following code shows only eight bits, but pretend there are 24 extra zeros on the left.) x = 47 // 47 is 00101111 in binary. x = x << 1 // 00101111 << 1 is 01011110.

Similarly, you use the right-shift operator >> to shift its first operand’s bits to the right. Bits shifted off the right side are discarded; new bits added on the left side either 0 or whatever value was previously in the leftmost bit position. x = 47 /* 47 is 00101111 in binary. */ x = x >> 1 /* 00101111 >> 1 is 00010111. */

The right-shift operator is syntactic sugar for foo << -bar. For both << and >>, if the second operand is negative, the shifting direction is flipped.

The shift operators can be used to perform a variety of hacks, such as storing extra values within a single integer, and seriously accelerating twos-complement multiplications or divisions.