Shift Operators (Advanced) |
Top Previous Next |

Those familiar with assembly language will recognize the shift operation. The general form of the shift expression is:
EXPR << EXPR or EXPR >> EXPR
EXPR is an integer sub-expression--a 16-bit value. "<<" means shift to the left, and ">>" means shift to the right. The value of the first sub-expression is shifted the number of bits specified by the second sub-expression. The value of the second sub-expression should range from 0 through 15. Beware that only the low five bits are used (except for the 8086). This means that attempting to shift 33 places shifts only one place, and attempting to shift -1 places shifts 31 places.
Here are some examples:
1 << 1 = 2 $30 << 2 = $C0 $50 >> 4 = $05 $FF5A >> 4 = $0FF5
The shift operator's precedence (priority) is between the unary operators and the multiplication and division operators. The following expressions show this:
-1>>8 * 2 = (-1 >> 8) * 2 = $01FE 2 + 1<<4 = 2 + (1 << 4) = $0012
Multiplying and dividing by powers of two is similar to doing a shift operation. However note that dividing a negative number gives a negative result, which is not the same as shifting the negative number to the right. Shift operations are faster than multiplying or dividing. |