Export (0) Print
Expand All

Bitwise Right Shift Operator (>>)

Right shifts the bits of an expression, maintaining sign.

expression1 >> expression2

expression1

Any numeric expression.

expression2

Any numeric expression.

The >> operator shifts the bits of expression1 right by the number of bits specified in expression2. The sign bit of expression1 is used to fill the digits from the left. Digits shifted off to the right are discarded. The data type of expression1 determines the data type returned by this operator.

The >> operator masks expression2 to avoid shifting expression1 by too much. Otherwise, if the shift amount exceeded the number of bits in the data type of expression1, all the original bits would be shifted away to give a trivial result. To ensure that each shift leaves at least one of the original bits, the shift operators use the following formula to calculate the actual shift amount: mask expression2 (using the bitwise AND operator) with one less than the number of bits in expression1.

For example, after the following code is evaluated, temp has a value of -4: -14 (11110010 in two's complement binary) shifted right two bits equals -4 (11111100 in two's complement binary).

var temp
temp = -14 >> 2

To illustrate how the masking works, consider the following example.

var x : byte = 15;
// A byte stores 8 bits.
// The bits stored in x are 00001111
var y : byte = x >> 10;
// Actual shift is 10 & (8-1) = 2
// The bits stored in y are 00000011
// The value of y is 3
print(y); // Prints 3

Community Additions

ADD
Show:
© 2014 Microsoft